diff options
Diffstat (limited to 'org.tizen.common/src/org/tizen')
169 files changed, 20119 insertions, 3105 deletions
diff --git a/org.tizen.common/src/org/tizen/common/Adaptable.java b/org.tizen.common/src/org/tizen/common/Adaptable.java new file mode 100644 index 000000000..8fb893549 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/Adaptable.java @@ -0,0 +1,49 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common; + +/** + * <p> + * Adaptable. + * + * Class for adapter pattern + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +Adaptable +{ + /** + * Adapt to new type interface or class + * + * @param <T> new type + * @param clazz new type class + * + * @return object to adapt to + */ + public <T> T adapt( Class<T> clazz ); +} diff --git a/org.tizen.common/src/org/tizen/common/AppIdGenerator.java b/org.tizen.common/src/org/tizen/common/AppIdGenerator.java new file mode 100644 index 000000000..1712b04e9 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/AppIdGenerator.java @@ -0,0 +1,127 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Changhyun Lee <changhyun1.lee@samsung.com> + * Hyeongseok Heo <hyeongseok.heo@samsung.com> + * BonYong Lee <bonyong.lee@samsung.com> + * Kangho Kim <kh5325.kim@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ + +package org.tizen.common; + +import java.math.BigInteger; +import java.security.SecureRandom; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Appid generator. + * It is consist of 0-9, a-z + */ +public class AppIdGenerator { + final char[] PSEUDO_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', + 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', + 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', + 'y', 'z' }; + + final BigInteger PSEUDO_CHAR_SIZE = new BigInteger("62"); + + // Reserved AppID (or prefix) + static final String RESERVED_APPID [] = { + "TIZEN", + "PRIVT", + "WIDGT" + }; + // Number of reserved AppID + static final int RESERVED_APPID_NUMBER = 3; + + private String convertBytesToAlphaNumeric(byte in[], int size) { + BigInteger randomBigInt = new BigInteger(in).abs(); + StringBuffer out = new StringBuffer(size + 1); + + for (int i = 0; i < size; ++i) { + BigInteger[] dividedAndremainder = randomBigInt.divideAndRemainder(PSEUDO_CHAR_SIZE); + randomBigInt = dividedAndremainder[0]; + out.append(PSEUDO_CHARS[dividedAndremainder[1].intValue()]); + } + + String ret = new String(out); + return ret; + } + + private byte[] generateRandomBytes(int size) throws Exception { + SecureRandom random = new SecureRandom(); + KeyGenerator keyGen = KeyGenerator.getInstance("AES"); + keyGen.init(128); + + byte[] bytes = new byte[size]; + random.nextBytes(bytes); + + SecretKey secretkey = keyGen.generateKey(); + byte[] key = secretkey.getEncoded(); + SecretKeySpec secretkeySpec = new SecretKeySpec(key, "AES"); + + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec); + + return cipher.doFinal(bytes); + } + + private boolean check(String appId) { + for (int i = 0; i < RESERVED_APPID_NUMBER; ++ i) { + if (appId.indexOf(RESERVED_APPID[i]) == 0) { + return false; + } + } + return true; + } + + /** + * Generate an id of length n. + * + * @param size id length + * @return id + */ + public String generate(int size) throws Exception { + String appId = ""; + do { + appId = convertBytesToAlphaNumeric(generateRandomBytes(size), size); + } while (!check(appId)); + + return appId; + } + + /** + * Generate an id of length 10. + * + * @return id + */ + public String generate() throws Exception { + return generate(10); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/Cabinet.java b/org.tizen.common/src/org/tizen/common/Cabinet.java new file mode 100755 index 000000000..5ed46d02c --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/Cabinet.java @@ -0,0 +1,10 @@ +package org.tizen.common;
+
+public interface
+Cabinet<T>
+extends Runnable
+{
+ public T getData();
+
+ public void setData( T data );
+}
diff --git a/org.tizen.common/src/org/tizen/common/CommonPlugin.java b/org.tizen.common/src/org/tizen/common/CommonPlugin.java index b337172d8..736d1d7d5 100644 --- a/org.tizen.common/src/org/tizen/common/CommonPlugin.java +++ b/org.tizen.common/src/org/tizen/common/CommonPlugin.java @@ -3,10 +3,10 @@ * * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. * -* Contact: +* Contact: * Changhyun Lee <changhyun1.lee@samsung.com> * Kangho Kim <kh5325.kim@samsung.com> -* +* * 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 @@ -25,16 +25,21 @@ */ package org.tizen.common; -import java.io.File; - +import org.apache.log4j.spi.RepositorySelector; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; -import org.tizen.common.preferences.TizenBasePreferencePage; -import org.tizen.common.properties.InstallPathConfig; +import org.tizen.common.core.application.InstallPathConfig; +import org.tizen.common.core.command.EclipseExecutor; +import org.tizen.common.core.command.Executor; +import org.tizen.common.core.command.Prompter; +import org.tizen.common.core.command.prompter.EclipsePrompter; +import org.tizen.common.core.command.prompter.SWTPrompter; +import org.tizen.common.ui.page.preference.TizenBasePreferencePage; +import org.tizen.common.util.DialogUtil; import org.tizen.common.util.HostUtil; import org.tizen.common.util.OSChecker; - +import org.tizen.common.util.log.Logger; import org.tizen.sdblib.SmartDevelopmentBridge; /** @@ -45,36 +50,69 @@ public class CommonPlugin extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.tizen.common"; //$NON-NLS-1$ - private final static String SDKSUFFIX = File.separatorChar+".TizenSDK"+File.separatorChar+"tizensdkpath"; // The shared instance private static CommonPlugin plugin; - + /** - * The constructor + * {@link Prompter} using swt dialog */ - public CommonPlugin() { - SmartDevelopmentBridge.init(); - String sdbPath = InstallPathConfig.getSDKPath() + File.separator + "SDK" + File.separator +"sdb" + File.separator + "sdb"; - SmartDevelopmentBridge.createBridge(sdbPath, true); - } + protected EclipsePrompter prompter = null; + + /** + * {@link Executor} with {@link SWTPrompter} + */ + protected Executor executor = null; + + protected RepositorySelector selector = null; /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ + @Override public void start(BundleContext context) throws Exception { - super.start(context); + super.start( context ); plugin = this; + initializeExecutor(); + + String sdbPath = InstallPathConfig.getSDBPath(); + if (!HostUtil.exists(sdbPath)) { + DialogUtil.openMessageDialog("There is no " + sdbPath + "."); + } + else { + try { + SmartDevelopmentBridge.init(); + SmartDevelopmentBridge.createBridge(sdbPath, true); + } catch (Throwable t) { + Logger.error("Problem occurred while initializing sdb", t.getMessage(), t); + DialogUtil.openErrorDialog("Failed to start sdb"); + } + } + + if (OSChecker.isWindows()) { + String dllPath = InstallPathConfig.getSdbWinUsbApiPath(); + if (!HostUtil.exists(dllPath)) + DialogUtil.openMessageDialog("There is no " + dllPath + ".\n" + + "It's not mandatory but you may have problem in using sdb through USB."); + } } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ + @Override public void stop(BundleContext context) throws Exception { + finalizeExecutor(); plugin = null; super.stop(context); } + + + public static void setDefault( CommonPlugin plugin ) + { + CommonPlugin.plugin = plugin; + } /** * Returns the shared instance @@ -84,39 +122,56 @@ public class CommonPlugin extends AbstractUIPlugin { public static CommonPlugin getDefault() { return plugin; } - - @Override - protected void initializeDefaultPreferences(IPreferenceStore store) { - if (loadSdkPath() != null) - store.setDefault(TizenBasePreferencePage.KEY_SDKLOCATION,loadSdkPath()); - store.setDefault(TizenBasePreferencePage.KEY_SDKUPDATE,TizenBasePreferencePage.VALUE_SDKUPDATE_DEFAULT); + /* (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore) + */ + @Override + protected void initializeDefaultPreferences( final IPreferenceStore store ) { + if (InstallPathConfig.getSDKPath() != null) + store.setDefault(TizenBasePreferencePage.KEY_SDKLOCATION, InstallPathConfig.getSDKPath()); + store.setDefault(TizenBasePreferencePage.KEY_SDKUPDATE, TizenBasePreferencePage.VALUE_SDKUPDATE_DEFAULT); + } - } + /** + * Set {@link Executor} in eclipse plugin environment + * + * @param executor {@link Executor} + */ + public void setExecutor( final Executor executor ) + { + this.executor = executor; + } + + /** + * Return {@link Executor} in eclipse plugin environment + * @return + */ + public Executor getExecutor() + { + return this.executor; + } + + /** + * Return {@link Prompter} in eclipse plugin environment + * + * @return {@link Prompter} + */ + public Prompter getPrompter() + { + return this.prompter; + } - - /** - * get sdk path - */ - private String loadSdkPath() { - String sdkConfig; - String sdkPath = null;; - if (OSChecker.isWindows()) - sdkConfig = System.getenv("localappdata") + File.separatorChar + SDKSUFFIX; - else - sdkConfig= System.getProperty("user.home") + File.separatorChar + SDKSUFFIX; + protected void initializeExecutor() + { + this.prompter = new EclipsePrompter( new SWTPrompter() ); + + this.executor = new EclipseExecutor( prompter ); + } - if (HostUtil.exists(sdkConfig)) { - String contents = HostUtil.getContents(sdkConfig); - if (contents != null) { - String[] fileContent = contents.split("="); - if (fileContent.length == 2) { - if (HostUtil.exists(fileContent[1])) - sdkPath = fileContent[1]; - } - } - } - return sdkPath; - } + protected void finalizeExecutor() + { + + } } diff --git a/org.tizen.common/src/org/tizen/common/model/DefaultTableModel.java b/org.tizen.common/src/org/tizen/common/Factory.java index d50073748..b5dcc5784 100644 --- a/org.tizen.common/src/org/tizen/common/model/DefaultTableModel.java +++ b/org.tizen.common/src/org/tizen/common/Factory.java @@ -1,43 +1,45 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-
-public class DefaultTableModel extends AbstractTableModel {
-
- public DefaultTableModel(AbstractTableVO source) {
- super(source);
- }
-
- public String getSourceName() {
- String str = this.source.getClass().getSimpleName();
- if(str.endsWith("VO")) //$NON-NLS-1$
- str = str.substring(0,str.length()-2);
- return str;
- }
-}
-
-
+/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* Hyeongseok Heo <hyeongseok.heo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* Gyeongseok Seo <gyeongseok.seo@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common; + +/** + * Factory Interface that are using when create new object by Factory pattern + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * @author Gyeongseok Seo <gyeongseok.seo@samsung.com> + */ +public interface Factory<T> +{ + /** + * create object + * + * @return created <code>T</code> object + */ + T create(); +} diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewContentProvider.java b/org.tizen.common/src/org/tizen/common/FactoryWithArgument.java index 2d9038cac..864e92ff2 100644 --- a/org.tizen.common/src/org/tizen/common/control/TableViewContentProvider.java +++ b/org.tizen.common/src/org/tizen/common/FactoryWithArgument.java @@ -1,50 +1,45 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.tizen.common.model.ITableModel;
-
-
-public class TableViewContentProvider implements IStructuredContentProvider {
-
- public TableViewContentProvider() {
- }
-
- public Object[] getElements(Object model) {
- return ((ITableModel)model).getDatas();
- }
-
- public void dispose() {
-
- }
-
- public void inputChanged(Viewer viewer, Object obj, Object obj1) {
-
- }
-
-}
+/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* Hyeongseok Heo <hyeongseok.heo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* Gyeongseok Seo <gyeongseok.seo@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common; + +/** + * Factory Interface that are using when create new object with argument by Factory pattern + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * @author Gyeongseok Seo <gyeongseok.seo@samsung.com> + */ +public interface FactoryWithArgument<T, A> { + /** + * create object + * + * @param arg argument of an object to be created + * @return created <code>T</code> object + */ + T create( A arg ); +} diff --git a/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java b/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java new file mode 100755 index 000000000..325223de2 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java @@ -0,0 +1,39 @@ +/*
+ * Common
+ *
+ * Copyright (C) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Jihoon Song <jihoon80.song@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+/**
+ * IApplicationConfiguration Interface that is used when getting project's build configurations.
+ *
+ * @author Kangho Kim{@literal <kh5325.kim@samsung.com>} (S-Core)
+ * @author Yoonki Park <yoonki.park@samsung.com>
+ */
+public interface IApplicationConfiguration {
+ public String getDefaultConfiguration();
+ public String getBinaryName();
+ public String generateAppId();
+ public TizenProjectType getTizenProjectType();
+}
diff --git a/org.tizen.common/src/org/tizen/common/Surrogate.java b/org.tizen.common/src/org/tizen/common/Surrogate.java new file mode 100644 index 000000000..c752d78e6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/Surrogate.java @@ -0,0 +1,44 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* Hyeongseok Heo <hyeongseok.heo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* Gyeongseok Seo <gyeongseok.seo@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common; + +/** + * Surrogate Interface that are using when dependency object is injected by surrogate pattern + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * @author Gyeongseok Seo <gyeongseok.seo@samsung.com> + */ +public interface Surrogate<T> { + /** + * pass adapted object + * + * @return adapted <code>T</code> object + */ + T getAdapter(); +} diff --git a/org.tizen.common/src/org/tizen/common/control/TreeViewLabelProvider.java b/org.tizen.common/src/org/tizen/common/SurrogateWithArgument.java index 77bb41387..d6b704db5 100644 --- a/org.tizen.common/src/org/tizen/common/control/TreeViewLabelProvider.java +++ b/org.tizen.common/src/org/tizen/common/SurrogateWithArgument.java @@ -1,32 +1,42 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.LabelProvider;
-
-public class TreeViewLabelProvider extends LabelProvider {
-
-}
+/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common; + +/** + * Surrogate Interface that are using when dependency object is injected by surrogate pattern + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface SurrogateWithArgument<T, A> +{ + /** + * pass adapted object using argument + * + * @param arg argument of an object to be created + * + * @return adapted <code>T</code> object + */ + T getAdapter( A arg ); +} diff --git a/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java b/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java new file mode 100644 index 000000000..c543ddcc8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java @@ -0,0 +1,49 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Changhyun Lee <changhyun1.lee@samsung.com> +* Kangho Kim <kh5325.kim@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common; + +public class TizenHelpContextIds +{ + public static final String HELP_COMMON_CONNECTION_EXPLORER_CONTEXT = "org.tizen.ide.common.connection_explorer_context"; + public static final String HELP_COMMON_LOG_CONTEXT = "org.tizen.ide.common.log_context"; + + public static final String HELP_NATIVE_CODECOVERAGE_CONTEXT = "org.tizen.ide.native.codecoverage_context"; + public static final String HELP_NATIVE_UNITTEST_CONTEXT = "org.tizen.ide.native.unittest_context"; + public static final String HELP_NATIVE_MANIFEST_CONTEXT = "org.tizen.ide.native.manifest_context"; + public static final String HELP_NATIVE_PROJECT_WIZARD_CONTEXT = "org.tizen.ide.native.project_wizard_context"; + + public static final String HELP_WEB_WIDGET_CONFIGURATION_EDITOR_CONTEXT = "org.tizen.ide.web.widget_configuration_editor_context"; + public static final String HELP_WEB_HTML_EDITOR_CONTEXT = "org.tizen.ide.web.html_editor_context"; + public static final String HELP_WEB_JAVASCRIPT_EDITOR_CONTEXT = "org.tizen.ide.web.javascript_editor_context"; + public static final String HELP_WEB_CSS_EDITOR_CONTEXT = "org.tizen.ide.web.css_editor_context"; + public static final String HELP_WEB_HTML_PREVIEW_CONTEXT = "org.tizen.ide.web.html_preview_context"; + public static final String HELP_WEB_CSS_PREVIEW_CONTEXT = "org.tizen.ide.web.css_preview_context"; + public static final String HELP_WEB_PREFERENCES_CONTEXT = "org.tizen.ide.web.preferences_context"; + public static final String HELP_WEB_SIMULATOR_PREFERENCES_CONTEXT = "org.tizen.ide.web.simulator_preferences_context"; + public static final String HELP_WEB_NEW_PROJECT_WIZARD_CONTEXT = "org.tizen.ide.web.new_project_wizard_context"; + public static final String HELP_WEB_USER_TEMPLATE_CONTEXT = "org.tizen.ide.web.user_template_context"; + +} diff --git a/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java b/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java new file mode 100644 index 000000000..2463a9822 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java @@ -0,0 +1,80 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* Hyunsik Noh <hyunsik.noh@samsung.com> +* Yoonki Park <yoonki.park@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common; + +import org.tizen.common.util.OSChecker; + +/** + * All constant definitions related Tizen Platform such as Emulator or Device. + * @author Kangho Kim {@literal <kh5325.kim@samsung.com>} (S-Core) + */ +public class TizenPlatformConstants { + // Definitions for common + public static final String LOCALHOST = "127.0.0.1"; + public static final String ENVIRONMENT_SETTING_CMD = "export "; + public static final String CMD_RESULT_CHECK = "; echo $?;"; + public static final String CMD_RESULT_PREFIX = "cmd_ret:"; + public static final String CMD_SUFFIX = "; echo "+CMD_RESULT_PREFIX+"$?;"; + public static final String CMD_SUCCESS = CMD_RESULT_PREFIX+"0"; + public static final String CMD_FAILURE = CMD_RESULT_PREFIX+"1"; + + public static final int OS = OSChecker.LINUX; + + // Definitions for building + + // Definitions for packaging + public static final String PACKAGENAME_PREFIX = "org.tizen"; + public static final String DEBIAN_INSTALL_PATH = "opt/*"; + + // Definitions for debugging + public static final String PUBICL_PLATFORM_CORE_PATH = "/opt/bs/core"; + public static final String PRIVATE_PLATFORM_CORE_PATH = "/opt/share/hidden_storage/SLP_debug"; + public static final String GDBSERVER_CMD = TizenPlatformConstants.TOOLS_TARGET_PATH + "/gdbserver/gdbserver"; + public static final String GDBSERVER_PLATFORM_CMD = TizenPlatformConstants.TOOLS_TARGET_PATH + "/gdbserver-platform/gdbserver"; + public static final String ATTACH_OPTION = " --attach "; + + // Definitions for installing + public static final String APP_INSTALL_PATH = "/opt/apps"; + public static final String TEMPORARY_PKG_PATH = "/opt/apps/PKGS/"; + public static final String PKG_TOOL_LIST_COMMAND = "pkgcmd -l | grep %s"; + public static final String PKG_TOOL_REMOVE_COMMAND = "pkgcmd -q -u -t %s -n %s"; + public static final String PKG_TOOL_INSTALL_COMMAND = "pkgcmd -q -i -t %s -p %s"; + + // Definitions for launching + public static final String LAUNCH_CMD = "launch_app %s"; + public static final String LAUNCH_CMD_SUCCESS = "... successfully launched"; + public static final String LAUNCH_CMD_FAILURE = "... launch failed"; + public static final String ELM_SCALE_GETTER = "/home/developer/sdk_tools/elm_scale_getter/get_elm_scale ";//FIXME : have to be removed + + // Definitions for ondemand install + public static final String CONTROL_EXTENSION = ".control"; + public static final String TOOLS_TARGET_PATH = "/home/developer/sdk_tools"; + + // Definitions for others + public static final String CODE_COVERAGE_BUILD_OPTION = "-fprofile-arcs -ftest-coverage"; + public static final String CODE_COVERAGE_LAUNCH_OPTION = " __AUL_SDK__ CODE_COVERAGE"; +} diff --git a/org.tizen.common/src/org/tizen/common/TizenProjectType.java b/org.tizen.common/src/org/tizen/common/TizenProjectType.java new file mode 100644 index 000000000..126151ba8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/TizenProjectType.java @@ -0,0 +1,41 @@ +/* +* TizenProjectType.java +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5225.kim@samsung.com> +* Gun Kim <gune.kim@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common; + +/** + * Represents that TIZEN supports the given project types. + */ +public enum TizenProjectType { + TIZEN_C_UI_APPLICATION, + TIZEN_C_SERVICE_APPLICATION, + TIZEN_C_SHAREDLIBRARY, + TIZEN_C_STATICLIBRARY, + TIZEN_CPP_UI_APPLICATION, + TIZEN_CPP_SERVICE_APPLICATION, + TIZEN_CPP_SHAREDLIBRARY, + TIZEN_CPP_STATICLIBRARY, + TIZEN_PLATFORM_PROJECT; +} diff --git a/org.tizen.common/src/org/tizen/common/cache/ImageCache.java b/org.tizen.common/src/org/tizen/common/cache/ImageCache.java deleted file mode 100644 index 639a79723..000000000 --- a/org.tizen.common/src/org/tizen/common/cache/ImageCache.java +++ /dev/null @@ -1,105 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Changhyun Lee <changhyun1.lee@samsung.com>
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-package org.tizen.common.cache;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * Class for caching images
- *
- * @author Emil
- */
-public class ImageCache {
-
- private static HashMap<String, Image> _ImageMap;
-
- // what path to get to the "icons" directory without actually including it
- private static final String ICON_ROOT_PATH = "icons/";
-
- static {
- _ImageMap = new HashMap<String, Image>();
- }
-
- /**
- * Returns an image that is also cached if it has to be created and does not already exist in the cache.
- *
- * @param fileName Filename of image to fetch
- * @return Image null if it could not be found
- */
- public static Image getImage(String fileName) {
- fileName = ICON_ROOT_PATH + fileName;
- Image image = _ImageMap.get(fileName);
- if (image == null) {
- image = createImage(fileName);
- _ImageMap.put(fileName, image);
- }
- return image;
- }
-
- // creates the image, and tries really hard to do so
- private static Image createImage(String fileName) {
- ClassLoader classLoader = ImageCache.class.getClassLoader();
- InputStream is = classLoader.getResourceAsStream(fileName);
- if (is == null) {
- // the old way didn't have leading slash, so if we can't find the image stream,
- // let's see if the old way works.
- is = classLoader.getResourceAsStream(fileName.substring(1));
-
- if (is == null) {
- is = classLoader.getResourceAsStream(fileName);
- if (is == null) {
- is = classLoader.getResourceAsStream(fileName.substring(1));
- if (is == null) { return null; }
- }
- }
- }
-
- Image img = new Image(Display.getDefault(), is);
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return img;
- }
-
- /**
- * Disposes ALL images that have been cached.
- */
- public static void dispose() {
- Iterator<Image> e = _ImageMap.values().iterator();
- while (e.hasNext())
- e.next().dispose();
-
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java b/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java deleted file mode 100644 index 6bbc54ede..000000000 --- a/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java +++ /dev/null @@ -1,136 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.tizen.common.model.ITableVO;
-
-
-/**
- * This class implements an ICellModifier
- * An ICellModifier is called when the user modifes a cell in the
- * tableViewer
- */
-
-public class TableViewCellModifier implements ICellModifier {
- private TableViewer viewer;
- private String[] columnNames;
- CellEditor[] cellEditors;
- /**
- * Constructor
- * @param TableViewerExample an instance of a TableViewerExample
- */
- public TableViewCellModifier(TableViewer viewer) {
- super();
- this.viewer = viewer;
- this.columnNames = getColumnNames();
- this.viewer.setColumnProperties(columnNames);
- }
-
- private String[] getColumnNames() {
- TableColumn[] columns = viewer.getTable().getColumns();
- String[] columnNames = new String[columns.length];
- for(int i=0;i<columnNames.length;i++){
- columnNames[i] = columns[i].getText();
- }
-
- return columnNames;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#canModify(java.lang.Object, java.lang.String)
- */
- public boolean canModify(Object element, String property) {
- return true;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#getValue(java.lang.Object, java.lang.String)
- */
- public Object getValue(Object element, String property) {
-
- Object result = null;
- int idx = getColumnIndex(property);
- ITableVO vo = (ITableVO)element;
-
- CellEditor ce = getCellEditor(idx);
-
- if(ce instanceof ComboBoxCellEditor){
- result = vo.getColumnValue(idx);
- }else if(ce instanceof TextCellEditor){
- result = vo.getColumnValue(idx);
- }else{
- result = ""; //$NON-NLS-1$
- }
- return result;
- }
-
- private CellEditor getCellEditor(int idx) {
- if(this.cellEditors==null)
- this.cellEditors = viewer.getCellEditors();
- return this.cellEditors[idx];
- }
-
- private int getColumnIndex(String property) {
- for(int i=0;i<columnNames.length;i++){
- if(columnNames[i].equals(property))
- return i;
- }
- return 0;
- }
-
- private int getComboIndex(String[] items, Object str) {
- for(int i=0;i<items.length;i++){
- if(items[i].equals(str))
- return i;
- }
- return 0;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#modify(java.lang.Object, java.lang.String, java.lang.Object)
- */
- public void modify(Object element, String property, Object value) {
- int idx = getColumnIndex(property);
- ITableVO vo = (ITableVO)((TableItem) element).getData();
-
- if(cellEditors[idx] instanceof ComboBoxCellEditor){
- if((Integer)value < 0)
- return;
- else
- vo.setColumnValue(idx, value);
- }else if(cellEditors[idx] instanceof TextCellEditor){
- vo.setColumnValue(idx, value);
- }
-
- viewer.update(vo, null);
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java b/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java deleted file mode 100644 index 1456f8928..000000000 --- a/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java +++ /dev/null @@ -1,160 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import java.util.Comparator;
-
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.tizen.common.model.ITableVO;
-
-
-
-
-/**
- * A viewer sorter is used by a structured viewer to reorder the elements
- * provided by its content provider. In addition, the TableViewColumnSorter
- * listens for mouse clicks in the column headers and resorts the table content
- * based on the column that was selected. Clicking on a column a second time
- * toggles the sort order.
- */
-public class TableViewColumnSorter extends ViewerSorter {
- private static final String COLUMN_INDEX_KEY = "COLUMN_INDEX"; //$NON-NLS-1$
- private static final String HEADER_TEXT_KEY = "HEADER_TEXT"; //$NON-NLS-1$
- private static final String TAG_DESCENDING = "\u25b2"; // up-pointing triangle
- private static final String TAG_ASCENDING = "\u25bc"; // down-pointing triangle
-
- private TableViewer viewer;
- private Table table;
- private TableColumn[] columns;
- Cursor waitCursor;
-
- private Comparator<String> stringComparator = new Comparator<String>(){
- @Override
- public int compare(String str1, String str2) {
- str1=str1==null?"":str1; //$NON-NLS-1$
- str2=str2==null?"":str2; //$NON-NLS-1$
- return str1.compareTo(str2);
- }
- };
-
- private Comparator<Integer> numberComparator = new Comparator<Integer>(){
- @Override
- public int compare(Integer num1, Integer num2) {
- return num1>num2?1:(num1==num2?0:-1);
- }
- };
-
- public TableViewColumnSorter(TableViewer viewer) {
- this.viewer = viewer;
- this.table = viewer.getTable();
- this.columns = viewer.getTable().getColumns();
-
- createCursor();
- createSelectionListener(columns);
- }
-
- private void createCursor(){
- waitCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_WAIT);
- }
-
- public int compare(Viewer viewer, Object object1, Object object2) {
- TableColumn column = table.getSortColumn();
-
- int index = -1;
- if(column==null){
- return 0;
- }else{
- index = (Integer)column.getData(COLUMN_INDEX_KEY);
- }
-
- Object target1 = ((ITableVO)object1).getColumnValue(index);
- Object target2 = ((ITableVO)object2).getColumnValue(index);
-
- int result = compare(target1, target2);
-
- if(table.getSortDirection()==SWT.UP)
- return result;
- else
- return -result;
- }
-
- public int compare(Object object1, Object object2){
- if(object1 instanceof Integer){
- return numberComparator.compare((Integer)object1, (Integer)object2);
- }else{
- return stringComparator.compare(object1.toString(), object2.toString());
- }
- }
-
- private void createSelectionListener(TableColumn[] columns) {
- for (int i = 0; i < columns.length; i++) {
- columns[i].setData(COLUMN_INDEX_KEY,i);
- columns[i].setData(HEADER_TEXT_KEY,columns[i].getText());
- columns[i].addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableColumn column = (TableColumn)e.getSource();
- clearColumnHeader(column);
- renderColumnHeader(column);
-
- table.setCursor(waitCursor);
- viewer.refresh();
- table.setCursor(null);
- }
- });
- }
- }
-
- private void renderColumnHeader(TableColumn column){
- int direction = table.getSortDirection()==SWT.UP?SWT.DOWN:SWT.UP;
- table.setSortDirection(direction);
- table.setSortColumn(column);
-
- String title = (String)column.getData(HEADER_TEXT_KEY);
- String directionShape = direction==SWT.UP?TAG_DESCENDING:TAG_ASCENDING;
- column.setText(title+" "+directionShape); //$NON-NLS-1$
- }
-
- private void clearColumnHeader(TableColumn column){
- TableColumn prevColumn = table.getSortColumn();
-
- if(prevColumn==null){
- return;
- }else{
- prevColumn.setText((String)prevColumn.getData(HEADER_TEXT_KEY));
- }
- }
-
-}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java b/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java deleted file mode 100644 index 12bfa05cb..000000000 --- a/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java +++ /dev/null @@ -1,121 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.graphics.Image;
-import org.tizen.common.model.ITableVO;
-
-
-
-
-
-public class TableViewLabelProvider extends ColumnLabelProvider implements ITableLabelProvider {
-
- public TableViewLabelProvider() {
- }
-
- private TableViewer viewer;
- CellEditor[] cellEditors;
-
- public TableViewLabelProvider(TableViewer viewer) {
- this.viewer = viewer;
- this.cellEditors = viewer.getCellEditors();
- }
-
- private Field[] fields;
-
- private int getColumnIndex(int columnIndex){
- return fields.length>columnIndex?columnIndex:fields.length;
- }
-
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
-// private void hasCellEditor(){
-// if(this.cellEditors==null)
-// this.cellEditors = viewer.getCellEditors();
-// }
-
- private CellEditor getCellEditor(int idx) {
- if(this.cellEditors==null)
- return null;
- else
- return this.cellEditors[idx];
- }
-
- public String getColumnText(Object element, int columnIndex) {
- Object obj = null;
-
- if(element instanceof ITableVO){
- ITableVO data = (ITableVO)element;
- if(this.cellEditors != null){
- CellEditor ce = getCellEditor(columnIndex);
- if(ce instanceof ComboBoxCellEditor){
- ComboBoxCellEditor editor = (ComboBoxCellEditor)ce;
- String items[] = editor.getItems();
- int idx = (Integer) data.getColumnValue(columnIndex);
- if(idx<0)
- obj = null;
- else if(idx>items.length)
- obj = items[0];
- else
- obj = items[idx];
- }else{
- obj = data.getColumnValue(columnIndex);
- }
- }else{
- obj = data.getColumnValue(columnIndex);
- }
- }else{
- if(fields==null)
- fields = element.getClass().getDeclaredFields();
-
- int idx = getColumnIndex(columnIndex);
- String fieldName = fields[idx].getName().substring(0, 1).toUpperCase()
- + fields[idx].getName().substring(1,fields[idx].getName().length());
-
- try{
- Method method = element.getClass().getMethod("get" + fieldName, new Class[] {}); //$NON-NLS-1$
- obj = method.invoke(element, new Object[] {});
- }catch(Exception e){
- return ""; //$NON-NLS-1$
- }
- }
-
- return obj==null?"":String.valueOf(obj); //$NON-NLS-1$
- }
-
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java b/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java deleted file mode 100644 index 726fb9390..000000000 --- a/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.tizen.common.model.ITreeModel;
-import org.tizen.common.model.ITreeVO;
-
-
-public class TreeViewContentProvider implements ITreeContentProvider {
-
- public Object[] getChildren(Object element) {
- if(element instanceof ITreeModel)
- return ((ITreeModel)element).getDatas();
- else
- return ((ITreeVO)element).getChildren();
- }
-
- public Object getParent(Object element) {
- if(element instanceof ITreeModel)
- return null;
- else
- return ((ITreeVO)element).getParent();
-
- }
-
- public boolean hasChildren(Object element) {
- if(element instanceof ITreeModel)
- return ((ITreeModel)element).size()>0;
- else
- return ((ITreeVO)element).hasChildren();
- }
-
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java b/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java new file mode 100644 index 000000000..d0d268e50 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java @@ -0,0 +1,212 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.core.application; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; + +import org.tizen.common.util.DialogUtil; +import org.tizen.common.util.HostUtil; +import org.tizen.common.util.OSChecker; + + + +final public class InstallPathConfig { + + private static String defaultHomePath; + private static String sdkInstallPath; + + private static final String DIR_PLATFORMS = "platforms"; + private static final String DIR_PLATFORMS_VER = "tizen2.0"; + private static final String DIR_SAMPLES = "samples"; + private static final String DIR_SNIPPETS = "snippets"; + private static final String DIR_ON_DEMAND = "on-demand"; + private static final String DIR_EMULATOR = "emulator"; + private static final String DIR_INSTALLER = "install-manager"; + private static final String DIR_TOOLS = "tools"; + private static final String DIR_LIBRARY = "library"; + private static final String DIR_SDK_DATA = "tizen-sdk-data"; + + private final static String SDKSUFFIX = DIR_SDK_DATA + File.separatorChar + "tizensdkpath"; + + // Registry Key + private static final String REGISTRY_PATH_OF_SHELL_FOLDER = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"; + // public static final String REGISTRY_APP_DATA_OF_SHELL_FOLDER = "AppData"; + private static final String REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER = "\"Local AppData\""; + // Value Column + private static final String REG_SZ = "REG_SZ"; + + static { + // FIXME : don't need the following lines if using environment variable + if (OSChecker.isWindows()) { + defaultHomePath = getRegistryValue(REGISTRY_PATH_OF_SHELL_FOLDER,REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER) ; + } else if (OSChecker.isLinux() == true || OSChecker.isUnix() == true || OSChecker.isMAC() == true) { + defaultHomePath = System.getProperty("user.home"); + } else { + DialogUtil.openMessageDialog(System.getProperty("os.name") + " is not supported currently."); + System.exit(0); + } + + loadSdkPath(defaultHomePath + File.separatorChar + SDKSUFFIX); + } + + /** + * @deprecated Use {@link #getSDKPath()} instead. + */ + @Deprecated + public static String getIDEPath() { + // FIXME : can't help but putting the code due to the Web IDE path , It has to be removed soon. + return System.getProperty("user.dir"); + } + + public static String getSDKPath() { + return sdkInstallPath; + } + + //This is temporary code to get platform version path(only for one). + //TODO: Should change to return string array type for various platform version paths. + public static String getPlatformVersionPath() + { + String path = null; + String platformPath = getSDKPath() + File.separator + DIR_PLATFORMS; + File platforms = new File(platformPath); + if(platforms.isDirectory()) + { + // platforms.listFiles[0] can cause undetermined result like platforms/tmp.ini/sample + path = platformPath + File.separator + DIR_PLATFORMS_VER; + } + return path; + } + + //TODO: Should change to get string array type for various platform version paths. + public static String getSamplesPath() + { + return getPlatformVersionPath() + File.separator + DIR_SAMPLES; + } + + //TODO: Should change to get string array type for various platform version paths. + public static String getSnippetsPath() + { + return getPlatformVersionPath() + File.separator + DIR_SNIPPETS; + } + + //TODO: Should change to get string array type for various platform version paths. + public static String getOnDemandPath() + { + return getPlatformVersionPath() + File.separator + DIR_ON_DEMAND; + } + + public static String getLibraryPath() { + return getSDKPath() + File.separator + DIR_LIBRARY; + } + + private static String getToolsPath() { + return getSDKPath() + File.separator + DIR_TOOLS; + } + + public static String getSDBPath() { + String toolsPath = getToolsPath(); + if (OSChecker.isWindows()) + return toolsPath + File.separator + "sdb.exe"; + else + return toolsPath + File.separator + "sdb"; + } + + public static String getSdbWinUsbApiPath() { + return getToolsPath() + File.separator + "SdbWinUsbApi.dll"; + } + + public static String getInstallManagerPath() { + return getSDKPath() + File.separator + DIR_INSTALLER; + } + + public static String getEmulatorPath() { + return getToolsPath() + File.separator + DIR_EMULATOR; + } + + public static String getUserHomePath() { + return defaultHomePath; + } + + public static String getUserDataPath() { + return getUserHomePath() + File.separator + DIR_SDK_DATA; + } + + private static void loadSdkPath(String sdkPath) { + boolean status = true; + if (HostUtil.exists(sdkPath)) { + String[] fileContent = HostUtil.getContents(sdkPath).split("="); + if (HostUtil.exists(fileContent[1])) + sdkInstallPath = fileContent[1]; + else { + status = false; + } + } else { + status = false; + } + + if (!status) { + DialogUtil.openMessageDialog("Tizen SDK is not installed properly."); + System.exit(0); + } + } + private static String getRegistryValue(String node, String key) { + if (!OSChecker.isWindows()) + return null; + + BufferedReader br = null; + String value = ""; + + String query = "reg query " + "\"" + node + "\" /v " + key; + try { + Process process = Runtime.getRuntime().exec(query); + String encoding = System.getProperty("sun.jnu.encoding"); + br = new BufferedReader(new InputStreamReader(process.getInputStream(), encoding)); + + String line = null; + while ((line = br.readLine()) != null) { + int index = line.indexOf(REG_SZ); + if (index >= 0) { + value = line.substring(index + REG_SZ.length()).trim(); + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return value; + } +}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/core/application/Messages.java b/org.tizen.common/src/org/tizen/common/core/application/Messages.java new file mode 100644 index 000000000..d0ec4ae2f --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/application/Messages.java @@ -0,0 +1,19 @@ +package org.tizen.common.core.application; + +import org.eclipse.osgi.util.NLS; + +public class Messages extends NLS +{ + private static final String BUNDLE_NAME = Messages.class.getName(); //$NON-NLS-1$ + public static String DIALOG_TITLE; + public static String ASK_FOR_UPDATE; + + public static String FileExistDialogTitle; + public static String FileExistMsg; + + static { + // initialize resource bundle + NLS.initializeMessages( BUNDLE_NAME, Messages.class ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/application/Messages.properties b/org.tizen.common/src/org/tizen/common/core/application/Messages.properties new file mode 100644 index 000000000..d3158eb98 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/application/Messages.properties @@ -0,0 +1,5 @@ +DIALOG_TITLE = Tizen SDK +ASK_FOR_UPDATE = Tizen SDK updates are available. Do you want to install them now? + +FileExistDialogTitle=Existing resource +FileExistMsg="{0}" already exists. Do you want to overwrite it? diff --git a/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java b/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java new file mode 100644 index 000000000..7d4fa259a --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java @@ -0,0 +1,80 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Kangho Kim <kh5325.kim@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.application; + +import org.eclipse.jface.action.IStatusLineManager; +import org.eclipse.ui.IViewPart; + +public class StatusLineMessageManager +{ + + protected final IStatusLineManager manager; + + /** + * Contructor with {@link IViewPart} + * + * @param part {@link IViewPart} to provide {@link IStatusLineManager} + */ + public StatusLineMessageManager( final IViewPart part ) + { + this( part.getViewSite().getActionBars().getStatusLineManager() ); + } + + /** + * Constructor with {@link IStatusLineManager} + * + * @param manager {@link IStatusLineManager} to manage status bar + */ + public StatusLineMessageManager( + final IStatusLineManager manager + ) + { + if ( null == manager ) + { // Fast Fail + throw new NullPointerException(); + } + this.manager = manager; + } + + /** + * Add error message at status bar + * + * @param message message to print out + */ + public void setErrorMessage( final String message ) + { + manager.setErrorMessage( message ); + } + + /** + * Add message at status bar + * + * @param message message to print out + */ + public void setMessage( final String message ) + { + manager.setMessage( message ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/update/UpdateManager.java b/org.tizen.common/src/org/tizen/common/core/application/UpdateManager.java index 1a171792a..0213b2790 100644..100755 --- a/org.tizen.common/src/org/tizen/common/update/UpdateManager.java +++ b/org.tizen.common/src/org/tizen/common/core/application/UpdateManager.java @@ -23,24 +23,24 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.update; +package org.tizen.common.core.application; + +import static org.tizen.common.util.SWTUtil.syncExec; import java.io.File; -import java.util.ResourceBundle; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IStartup; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.tizen.common.CommonPlugin; -import org.tizen.common.preferences.TizenBasePreferencePage; -import org.tizen.common.properties.InstallPathConfig; +import org.tizen.common.ui.page.preference.TizenBasePreferencePage; import org.tizen.common.util.HostUtil; import org.tizen.common.util.OSChecker; +import org.tizen.common.util.SWTUtil; public class UpdateManager implements IStartup { @@ -48,49 +48,48 @@ public class UpdateManager implements IStartup { private static final String EXECUTE_INSTALLER_COMMAND_FOR_WINDOWS = "InstManager.exe"; private static final String UPDATE_LIST_CHECK_COMMAND = "%s -checkPackageUpdate"; private static final String RESULT_VALUE_OF_UPDATABLE = "updatable"; - private static final String BUNDLE_NAME = UpdateManager.class.getPackage().getName() + ".UpdateMessages";//$NON-NLS-1$ - - public static ResourceBundle resources = ResourceBundle.getBundle(BUNDLE_NAME); final IWorkbench workbench = PlatformUI.getWorkbench(); @Override public void earlyStartup() { // Check installable package exist. - IPreferenceStore prefStore = CommonPlugin.getDefault().getPreferenceStore(); + final IPreferenceStore prefStore = + CommonPlugin.getDefault().getPreferenceStore(); - if(prefStore.getBoolean(TizenBasePreferencePage.KEY_SDKUPDATE)) - { - boolean updatable = isExistUpdatablePackage(); - if(updatable) { - if(askExecuteInstallerDlg()) { - executeInstallManger(); - if (workbench != null) { - final Display display = workbench.getDisplay(); - display.syncExec(new Runnable() { - public void run() { - if (!display.isDisposed()) - workbench.close(); - } - }); - } - } - } + if ( !prefStore.getBoolean( TizenBasePreferencePage.KEY_SDKUPDATE ) ) + { // User don't want to update at startup + return ; } + if ( !isExistUpdatablePackage() ) + { // Check updatable version + return ; + } + if( !askExecuteInstallerDlg() ) + { // User don't want to update at this time + return ; + } + + executeInstallManger(); + syncExec( new Runnable() { + public void run() { + if (!workbench.getDisplay().isDisposed()) + { + workbench.close(); + } + } + }); } - private boolean isExistUpdatablePackage() { - String result = HostUtil.returnExecute(getUpdateCheckCmd(), InstallPathConfig.getInstallManagerPath()); - if(RESULT_VALUE_OF_UPDATABLE.equals(result)) - return true; - return false; + private boolean isExistUpdatablePackage() + { + String result = HostUtil.returnExecute( getUpdateCheckCmd(), InstallPathConfig.getInstallManagerPath() ); + return ( RESULT_VALUE_OF_UPDATABLE.equals( result ) ); } private boolean askExecuteInstallerDlg() { int ret = checkUpdate(); - if (ret == IDialogConstants.YES_ID) - return true; - return false; + return ( ret == IDialogConstants.YES_ID ); } private void executeInstallManger() { @@ -112,8 +111,11 @@ public class UpdateManager implements IStartup { MessageDialog dialog = new MessageDialog( PlatformUI.getWorkbench().getDisplay().getActiveShell(), - resources.getString("message.dialogTitle"), - null, resources.getString("message.askForUpdate"), MessageDialog.QUESTION, labels, 0); + Messages.DIALOG_TITLE, + null, + Messages.ASK_FOR_UPDATE, + MessageDialog.QUESTION, + labels, 0); dialog.open(); if (dialog.getReturnCode() == SWT.DEFAULT) { // A window close returns SWT.DEFAULT - mapped to a cancel @@ -124,7 +126,8 @@ public class UpdateManager implements IStartup { } }; - PlatformUI.getWorkbench().getDisplay().syncExec(query); + + SWTUtil.syncExec( query ); return result[0]; } diff --git a/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java b/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java new file mode 100644 index 000000000..a083ddc14 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java @@ -0,0 +1,94 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p> + * AbstractCommand. + * + * Abstract class for {@link Command} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +abstract public class +AbstractCommand<T> +implements Command<T> { + + /** + * Logger for this instance ( it will be used by sub-class ) + */ + protected Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Name of the cancel operation) + */ + public static final String COMMAND_CANCEL = "cancel"; + + /** + * Result after execution of command + */ + protected T result; + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Command#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + abstract public + void + run( + final Executor executor, + final ExecutionContext context + ) + throws Exception; + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Command#undo(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + public void undo( + final Executor executor, + final ExecutionContext context + ) + throws Exception + { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Command#getResult() + */ + @Override + public + T + getResult() + { + return this.result; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/Command.java b/org.tizen.common/src/org/tizen/common/core/command/Command.java new file mode 100644 index 000000000..c1b3f198e --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/Command.java @@ -0,0 +1,69 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command; + +/** + * <p> + * Command. + * + * Behavior unit for functionality independing on environment( file system, ui, ... ) + * </p> + * + * @param <T> Execution result type + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +Command<T> +{ + /** + * Execute unit functionality + * + * @param executor execution subject + * @param context execution context + * + * @throws Exception If Exception occur in execution + */ + void run( Executor executor, ExecutionContext context ) throws Exception; + + /** + * Execute undoing for execution if possible + * + * @param executor execution subject + * @param context execution context + * + * @throws Exception If Exception occur in undo + */ + void undo( Executor executor, ExecutionContext context ) throws Exception; + + /** + * Return execution result + * + * @return Execution result + */ + T getResult(); + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java b/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java new file mode 100644 index 000000000..c4e2b5758 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java @@ -0,0 +1,45 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Ho Namkoong <ho.namkoong@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ + +package org.tizen.common.core.command; + +/** + * <p> + * CommandCancelException. + * + * This exception is thrown when run method of command is canceled by user operation. + * </p> + * + * @param <T> Execution result type + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + * @See Command + */ + +public class CommandCancelException extends RuntimeException { + + private static final long serialVersionUID = 1L; + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java b/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java new file mode 100644 index 000000000..4fdfba554 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java @@ -0,0 +1,103 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * <p> + * CompositeCommand. + * + * Command to execute multiple {@link Command}s + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +CompositeCommand +extends AbstractCommand<Object> +{ + + /** + * {@link Command}s to execute + */ + @SuppressWarnings("rawtypes") + protected final ArrayList<Command> commands = new ArrayList<Command>(); + + /** + * Constructor with {@link Command}s + * + * @param commands {@link Command}s to execute + * + * @see #addCommand(Command...) + */ + public + CompositeCommand( + final Command<?>... commands + ) + { + addCommand( commands ); + } + + /** + * Add {@link Command} to {@link Command}s to execute + * + * @param commands + * + * @see #commands + */ + public + void + addCommand( + final Command<?>... commands + ) + { + if ( null != commands ) + { + this.commands.addAll( Arrays.asList( commands ) ); + } + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Command#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + public + void + run( + final Executor executor, + final ExecutionContext context + ) + throws Exception + { + for ( final Command<Object> command : this.commands ) + { + command.run( executor, context ); + } + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java b/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java new file mode 100644 index 000000000..ff02a58d3 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java @@ -0,0 +1,70 @@ +package org.tizen.common.core.command; + +import java.text.MessageFormat; + +import org.tizen.common.Factory; +import org.tizen.common.core.command.policy.PolicyRegistry; +import org.tizen.common.file.EclipseFileHandler; +import org.tizen.common.file.FileHandler; + +public class +EclipseExecutor +extends Executor +{ + /** + * Contructor with prompter + * + * @param prompter {@link Prompter} + */ + public + EclipseExecutor( + final Prompter prompter + ) + { + super( + new Factory<ExecutionContext>() { + + /** + * {@link FileHandler} for Command Line Interface + */ + protected FileHandler fileHandler = new EclipseFileHandler(); + + + /** + * <p> + * {@link PolicyRegistry} for Command Line Interface + * </p> + */ + protected Factory<PolicyRegistry> factory = new PolicyRegistryFactory(); + + /** + * Create and return {@link PolicyRegistry} + * + * @return {@link PolicyRegistry} to be created + */ + protected + PolicyRegistry + getRegistry() + { + return factory.create(); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.ExecutionContextFactory#create() + */ + @Override + public + ExecutionContext + create() + { + return new ExecutionContext( + getRegistry(), + prompter, + fileHandler + ); + } + + } + ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java b/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java new file mode 100644 index 000000000..0d68c2cf4 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java @@ -0,0 +1,138 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import org.tizen.common.core.command.policy.PolicyRegistry; +import org.tizen.common.file.FileHandler; + +/** + * <p> + * ExecutionContext. + * + * Context in execution of commands + * + * Container for objects in execution envitonment + * + * It is injected by executor + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see Executor + */ +public class +ExecutionContext +{ + /** + * Registry for {@link Policy} + */ + protected final PolicyRegistry registry; + + /** + * {@link Prompter} for user interaction + */ + protected final Prompter prompter; + + /** + * {@link FileHandler} for file system + */ + protected final FileHandler fileHandler; + + + /** + * Constructor with {@link PolicyRegistry}, {@link Prompter} and {@link FileHandler} + * + * @param registry {@link PolicyRegistry} to use + * @param prompter {@link Prompter} to use + * @param fileHandler {@link FileHandler} to use + */ + public + ExecutionContext( + final PolicyRegistry registry, + final Prompter prompter, + final FileHandler fileHandler + ) + { + this.registry= registry; + this.prompter = prompter; + this.fileHandler = fileHandler; + } + + + /** + * Return {@link PolicyRegistry} to be using + * + * @return {@link PolicyRegistry} + */ + public + PolicyRegistry + getPolicyRegistry() + { + return this.registry; + } + + /** + * Return {@link Policy} for <code>name</code> + * + * @param name policy name + * + * @return {@link Policy} matching by <code>name<code> + * + * @see PolicyRegistry#getPolicy(String); + */ + public + Policy + getPolicy( + final String name + ) + { + return this.registry.getPolicy( name ); + } + + /** + * Return {@link Prompter} to be using + * + * @return {@link Prompter} + */ + public + Prompter + getPrompter() + { + return this.prompter; + } + + /** + * Return {@link FileHandler} to be using + * + * @return {@link FileHandler} + */ + public + FileHandler + getFileHandler() + { + return this.fileHandler; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/Executor.java b/org.tizen.common/src/org/tizen/common/core/command/Executor.java new file mode 100644 index 000000000..6cd4e291a --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/Executor.java @@ -0,0 +1,213 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import static org.tizen.common.core.command.Policy.EXCEPTION_UNHANDLED; + +import java.lang.Thread.UncaughtExceptionHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.Factory; + + +/** + * <p> + * Executor. + * + * Execute command in specific environment + * + * Environment is specified by {@link #contextFactory} + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +Executor +{ + /** + * Logger for this instance + */ + protected Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Factory for {@link ExecutionContext} + */ + protected Factory<ExecutionContext> contextFactory; + + /** + * Cabinet for {@link ExecutionContext} + * + * Context is sustain in execution and destroy after exection + * + * @see #contextFactory + */ + protected ThreadLocal<ExecutionContext> contexts = new ThreadLocal<ExecutionContext>() + { + /* (non-Javadoc) + * @see java.lang.ThreadLocal#initialValue() + */ + @Override + protected + ExecutionContext + initialValue() + { + if ( null == contextFactory ) + { + return null; + } + return contextFactory.create(); + }; + }; + + /** + * Default constructor + */ + public + Executor() + { + } + + /** + * Constructor with context factory + * + * @param factory context factory to use + * + * @see #setContextFactory(Factory) + */ + public + Executor( + final Factory<ExecutionContext> factory + ) + { + setContextFactory( factory ); + } + + /** + * Return context factory + * + * @return context factory in use + */ + public + Factory<ExecutionContext> + getContextFactory() + { + return this.contextFactory; + } + + /** + * Set context factory + * + * @param factory context factory to use + */ + public + void + setContextFactory( + final Factory<ExecutionContext> factory + ) + { + logger.info( "ExecutionContextFactory :{}", factory ); + this.contextFactory = factory; + } + + /** + * Execute <code>commands</code> + * + * @param commands {@link Command}s + */ + public + void + execute( + final Command<?>... commands + ) + { + logger.trace( "Commands :{}", commands ); + contexts.remove(); + + execute( contexts.get(), commands ); + + } + public + void + execute( + final ExecutionContext context, + final Command<?>... commands + ) + { + + try { + for ( final Command<?> command : commands ) + { + command.run( this, context ); + } + } catch ( final Exception e ) { + final Policy policy = context.getPolicy( EXCEPTION_UNHANDLED ); + if ( null == policy ) + { // No policy + logger.error( "Error occured", e ); + return ; + } + + final UncaughtExceptionHandler handler = policy.adapt( UncaughtExceptionHandler.class ); + if ( null == handler ) + { + throw new IllegalStateException( e ); + } + handler.uncaughtException( Thread.currentThread(), e ); + } + finally + { + contexts.remove(); + } + } + + /** + * Execute <code>command</code> in <code>context</code> + * + * @param command {@link Command} to run + * @param context {@link ExecutionContext} to run in + */ + public void + run( + final Command<?> command, + final ExecutionContext context + ) + throws Exception + { + command.run( this, context ); + } + + /** + * Return {@link ExecutionContext} in context + * + * @return {@link ExecutionContext} + */ + public ExecutionContext + getContext() + { + return contexts.get(); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/Policy.java b/org.tizen.common/src/org/tizen/common/core/command/Policy.java new file mode 100644 index 000000000..479d2f344 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/Policy.java @@ -0,0 +1,154 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import org.tizen.common.Adaptable; + + +/** + * <p> + * Policy. + * + * Adapter to other class when specific situation + * + * Situation specification is defined by naming rule + * + * Situation is define hierachically and is like tree structure + * + * Situation name has qualified name separating dot( '.' ). + * + * Each name fragment means node name in tree and qualified name stands for unique path. + * + * If there is no matching policy in registry, it provide policy having least distance. + * + * <ul> + * <li>nonexist + * <ul> + * <li>file + * <ul> + * <li>in</li> + * </ul> + * </li> + * <li>dir + * <ul> + * <li>in + * <ul> + * <li>project</li> + * </ul> + * </li> + * </ul> + * </li> + * </ul> + * </li> + * <li>exist + * <ul> + * <li>file + * <ul> + * <li>out + * <ul> + * <li>wgt</li> + * </ul> + * </li> + * </ul> + * </ul> + * </li> + * <li>exception + * <ul> + * <li>unhandled</li> + * <li>file + * <ul> + * <li>out + * <ul> + * <li>wgt</li> + * </ul> + * </li> + * </ul> + * </li> + * </ul> + * </li> + * </ul> + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +Policy +extends Adaptable +{ + /** + * When input file doesn't exist + */ + String NONEXIST_IN_FILE = "nonexist.file.in"; + + /** + * When input sign profile + */ + String NONEXIST_IN_FILE_SIGN_PROFILE = "nonexist.file.in.signprofile"; + + /** + * When input directory doesn't exist + */ + String NONEXIST_IN_DIRECTORY = "nonexist.dir.in"; + + /** + * When input project directory doesn't exist + */ + String NONEXIST_IN_PROJECT = "nonexist.dir.in.project"; + + /** + * When output file already exists + */ + String EXIST_OUT_FILE = "exist.file.out"; + /** + * When output widget file already exists + */ + String EXIST_OUT_WGT = "exist.file.out.wgt"; + + /** + * When target file is already exist. + */ + String EXIST_FILE_WHEN_COPY = "exist.file.when.copy"; + + /** + * When unexpected exception occured + */ + String EXCEPTION_UNHANDLED = "exception.unhandled"; + /** + * When exception occured in handling output widget file + */ + String EXCEPTION_OUT_WGT = "exception.file.out.wgt"; + + String PRINTOUT_RESULT_SIGNING = "printout.result.signing"; + + /** + * Return policy name + * + * policy name is unique indentifier + * + * @return policy name + */ + String getName(); +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java b/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java new file mode 100644 index 000000000..d055af04d --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java @@ -0,0 +1,240 @@ +/* + * Web IDE - Command Line Interface + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import static org.tizen.common.core.command.Policy.EXIST_OUT_FILE; +import static org.tizen.common.core.command.Policy.NONEXIST_IN_FILE; +import static org.tizen.common.core.command.Policy.EXIST_FILE_WHEN_COPY; +import static org.tizen.common.core.command.Policy.EXCEPTION_UNHANDLED; +import java.io.File; +import org.tizen.common.Factory; +import org.tizen.common.core.command.policy.AbstractPolicy; +import org.tizen.common.core.command.policy.FilePolicy; +import org.tizen.common.core.command.policy.MessagePolicy; +import org.tizen.common.core.command.policy.OptionPolicy; +import org.tizen.common.core.command.policy.PolicyRegistry; +import org.tizen.common.core.command.policy.UncaughtExceptionHandlingPolicy; +import org.tizen.common.core.command.prompter.RunableOption; +import org.tizen.common.file.StandardFileHandler; + +/** + * <p> + * PolicyRegistryFactory. + * + * {@link Factory} to provide {@link PolicyRegistry} in eclipse ide + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +PolicyRegistryFactory +implements Factory<PolicyRegistry> +{ + /** + * <p> + * CLIPolicy. + * + * {@link Policy} when command line interface + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see PolicyRegistry, {@link Policy} + */ + class EclipsePolicy + extends AbstractPolicy + { + /** + * <p> + * Constructor with <code>name</code> + * </p> + * + * @param name policy name + */ + public EclipsePolicy( final String name ) + { + super( name ); + } + + /* (non-Javadoc) + * @see org.tizen.common.Adaptable#adapt(java.lang.Class) + */ + @Override + @SuppressWarnings("unchecked") + public <T> + T + adapt( + final Class<T> clazz + ) + { + if ( clazz.isAssignableFrom( FilePolicy.class ) ) + { + return (T) FilePolicy.STOP_PROCESS; + } + else if ( clazz.isAssignableFrom( MessagePolicy.class) ) + { + return (T) MessagePolicy.PROMPTER; + } + else if ( clazz.isAssignableFrom(UncaughtExceptionHandlingPolicy.class)) + { + return (T) UncaughtExceptionHandlingPolicy.INSTANCE; + } + return null; + } + + } + /* (non-Javadoc) + * @see org.tizen.common.Factory#create() + */ + @Override + public + PolicyRegistry + create() + { + final PolicyRegistry registry = new PolicyRegistry(); + + registry.register( new EclipsePolicy( EXIST_FILE_WHEN_COPY ) { + @SuppressWarnings("unchecked") + @Override + public <T> T adapt(Class<T> clazz) { + if(clazz.isAssignableFrom(OptionPolicy.class)) { + + RunableOption overwrite = new RunableOption("overwrite") { + + private StandardFileHandler handler = new StandardFileHandler(); + + @Override + public void runWithArgument(Object... args) throws Exception { + if(args.length != 2) { + throw new IllegalArgumentException("argument length is wrong"); + } + + if(!(args[0] instanceof File && args[1] instanceof File)) { + throw new IllegalArgumentException("argument type is wrong"); + } + + File sourceFile = ((File)args[0]); + File targetFile = ((File)args[1]); + + handler.copyFile(sourceFile.getPath(), targetFile.getPath()); + } + + @Override + public boolean isDefault() { + return false; + } + }; + + RunableOption ignore = new RunableOption("ignore") { + + @Override + public boolean isDefault() { + return true; + } + + @Override + protected void runWithArgument(Object... args) throws Exception{ + } + }; + + RunableOption overwriteAll = new RunableOption("overwriteAll") { + + private StandardFileHandler handler = new StandardFileHandler(); + + @Override + public boolean isDefault() { + return false; + } + + @Override + protected void runWithArgument(Object... args) throws Exception { + super.setAllFlag(true); + + if(args.length != 2) { + throw new IllegalArgumentException("argument length is wrong"); + } + + if(!(args[0] instanceof File && args[1] instanceof File)) { + throw new IllegalArgumentException("argument type is wrong"); + } + + File sourceFile = ((File)args[0]); + File targetFile = ((File)args[1]); + + handler.copyFile(sourceFile.getPath(), targetFile.getPath()); + } + }; + + RunableOption ignoreAll = new RunableOption("ignoreAll") { + + @Override + public boolean isDefault() { + return false; + } + + @Override + protected void runWithArgument(Object... args) throws Exception{ + super.setAllFlag(true); + } + }; + + RunableOption cancel = new RunableOption("cancel") { + + @Override + public boolean isDefault() { + return false; + } + + @Override + protected void runWithArgument(Object... args) throws Exception{ + } + }; + + return (T)(new OptionPolicy(overwrite, ignore, overwriteAll, ignoreAll, cancel)); + } + return super.adapt(clazz); + } + }); + + registry.register(new EclipsePolicy(EXCEPTION_UNHANDLED) { + + @SuppressWarnings("unchecked") + @Override + public <T> T adapt(Class<T> clazz) { + if ( clazz.isAssignableFrom(UncaughtExceptionHandlingPolicy.class)) + { + return (T) UncaughtExceptionHandlingPolicy.INSTANCE; + } + return null; + } + }); + registry.register( new EclipsePolicy(EXIST_OUT_FILE)); + registry.register( new EclipsePolicy( NONEXIST_IN_FILE ) ); + + return registry; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/Prompter.java b/org.tizen.common/src/org/tizen/common/core/command/Prompter.java new file mode 100644 index 000000000..a76752b74 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/Prompter.java @@ -0,0 +1,94 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command; + +import org.tizen.common.core.command.prompter.Option; + +/** + * <p> + * Prompter. + * + * Handle user interaction + * <ul> + * <li>user input</li> + * <li>message output</li> + * <ul> + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +Prompter +{ + /** + * <p> + * Input user selection. + * + * The selection must be in <code>options</code> + * </p> + * + * @param question selection message + * @param options options to choice + * + * @return user selection + */ + Option interact( final String question, final Option... options ); + + /** + * <p> + * Input user input as password + * + * Password must be secured + * </p> + * + * @param message message for user password + * + * @return user input as password + */ + char[] password( String message ); + + /**<p> + * Print out error message + * </p> + * + * @param message error message + */ + void error( final String message ); + + /** + * Print out information message to notify + * + * @param message notification message + */ + void notify( final String message ); + + /** + * User cancle work in process + */ + void cancel(); + + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java new file mode 100644 index 000000000..d1ea1f65b --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java @@ -0,0 +1,145 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.file; + +import java.io.File; +import java.util.List; +import java.util.Stack; + +import org.tizen.common.core.command.AbstractCommand; +import org.tizen.common.core.command.CommandCancelException; +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.core.command.Policy; +import org.tizen.common.core.command.policy.OptionPolicy; +import org.tizen.common.core.command.prompter.Option; +import org.tizen.common.core.command.prompter.RunableOption; +import org.tizen.common.file.StandardFileHandler; +import org.tizen.common.util.log.Logger; + +/** + * <p> + * DirectoryCopyHandlingCommand. + * This class is used for copying source directory to the target directory. + * {@link FileHandlingCommand} + * </p> + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + */ + +public class DirectoryCopyHandlingCommand extends FileHandlingCommand<Boolean> { + + /** + * List of target path + */ + protected List<String> targetPathList; + + /** + * List of source path + */ + protected List<String> sourcePathList; + + public DirectoryCopyHandlingCommand(List<String> sourcePathList, List<String> targetPathList) throws IllegalArgumentException{ + if(sourcePathList.size() != targetPathList.size()) { + throw new IllegalArgumentException("Lenghs of sourcePathList and target paths are not same"); + } + this.sourcePathList = sourcePathList; + this.targetPathList = targetPathList; + } + + + @Override + public void run(Executor executor, ExecutionContext context) + throws Exception { + StandardFileHandler handler = new StandardFileHandler(); + Policy policy = context.getPolicy(Policy.EXIST_FILE_WHEN_COPY); + OptionPolicy optionPolicy = policy.adapt( OptionPolicy.class ); + Option[] options = optionPolicy.getOptions(); + + for(Option option: options) { + if(!(option instanceof RunableOption)) { + throw new IllegalArgumentException("Option " + option.getName() + " is not RunnableOption"); + } + } + + for(int i =0; i< sourcePathList.size(); i++) { + String sourcePath = sourcePathList.get(i); + String targetPath = targetPathList.get(i); + + final Stack<File> sourceStack = new Stack<File>(); + final Stack<File> targetStack = new Stack<File>(); + sourceStack.push( new File(sourcePath ) ); + targetStack.push( new File( targetPath ) ); + + while ( !sourceStack.isEmpty() ) + { + final File sourceFile = sourceStack.pop(); + final File targetFile = targetStack.pop(); + + if ( sourceFile.isDirectory() ) + { + handler.makeDirectory(targetFile.getPath()); + for ( final File sourceChild : sourceFile.listFiles() ) + { + sourceStack.push( sourceChild ); + targetStack.push( new File( targetFile, sourceChild.getName() ) ); + } + } + else if(sourceFile.isFile()) { + if(targetFile.exists()) { + boolean selectionDone = false; + RunableOption resultOption = null; + + for (Option option : options) { + if(((RunableOption)option).isAllFlag()) { + resultOption = (RunableOption)option; + selectionDone = true; + break; + } + } + + if(!selectionDone) { + resultOption = (RunableOption)context.getPrompter().interact(targetFile.getCanonicalPath() + " already exist", options); + } + if(AbstractCommand.COMMAND_CANCEL.equals(resultOption.getName())) { + throw new CommandCancelException(); + } + + resultOption.setArgument(sourceFile, targetFile); + resultOption.run(); + } + else { + System.out.println(targetFile); + targetFile.createNewFile(); + handler.copyFile(sourceFile.getPath(), targetFile.getPath()); + } + } + else { + Logger.error(sourceFile + " is not file or directory"); + } + } + } + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java new file mode 100644 index 000000000..78f079e27 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java @@ -0,0 +1,192 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.file; + +import org.tizen.common.FactoryWithArgument; +import org.tizen.common.core.command.AbstractCommand; +import org.tizen.common.core.command.Command; +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.file.Filter; +import org.tizen.common.file.SimpleFileFilter; +import org.tizen.common.file.filter.WildCardFilterFactory; + +/** + * FileHandlingCommand. + * + * Abstract class for file handling {@link Command} + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +FileHandlingCommand<T> +extends AbstractCommand<T> +{ + /** + * Factory to create file name pattern filter + */ + protected FactoryWithArgument<Filter, String> filterFactory = new WildCardFilterFactory(); + + /** + * File name filter + */ + protected SimpleFileFilter filter = new SimpleFileFilter(); + + /** + * Handling main path + */ + protected String path; + + /** + * Set filter factory + * + * @param factory {@link FactoryWithArgument<Filter, String>} + * + * @see WildCardFilterFactory + */ + public + void + setFilterFactory( + final FactoryWithArgument<Filter, String> factory + ) + { + this.filterFactory = factory; + logger.debug( "Configured filter factory :{}", factory ); + } + + /** + * Set filter + * @param filter {@link SimpleFileFilter} + */ + public + void + setFilter( SimpleFileFilter filter ) + { + if ( null == filter ) + { + throw new NullPointerException(); + } + this.filter = filter; + logger.debug( "Configured filter :{}", filter ); + } + + /** + * Set including file name patterns + * + * @param includes including file name patterns + */ + public + void + setIncludes( + final String[] includes + ) + { + filter.clearIncludes(); + if ( null != includes ) + { + for ( final String include : includes ) + { + filter.addIncludes( filterFactory.create( include ) ); + } + } + } + + /** + * Set excluding file name patterns + * + * @param excludes excluding file name patterns + */ + public + void + setExcludes( + final String[] excludes + ) + { + filter.clearExcludes(); + if ( null != excludes ) + { + for ( final String exclude : excludes ) + { + filter.addExcludes( filterFactory.create( exclude ) ); + } + } + } + + /** + * Return main working path + * + * @return {@link #path} + */ + public + String + getPath() + { + return this.path; + } + + /** + * Set main working path + * + * @param path main working path + */ + public + void + setPath( + final String path + ) + { + this.path = path; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.AbstractCommand#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + public + void + run( + final Executor executor, + final ExecutionContext context + ) + throws Exception + { + throw new UnsupportedOperationException(); + + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.AbstractCommand#undo(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + public + void + undo( + final Executor executor, + final ExecutionContext context + ) + throws Exception { + throw new UnsupportedOperationException(); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java new file mode 100644 index 000000000..9b60e18a5 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java @@ -0,0 +1,40 @@ +package org.tizen.common.core.command.file; + +import java.io.ByteArrayInputStream; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.ObjectUtil; + +public class +WriteFileCommand +extends FileHandlingCommand<Boolean> +{ + protected final byte[] contents; + + public WriteFileCommand( final String path, final byte[] contents ) + { + setPath( path ); + this.contents = contents; + } + + @Override + public + void + run( + final Executor executor, + final ExecutionContext context + ) + throws Exception + { + final byte[] safeBytes = ObjectUtil.nvl( contents, new byte[0] ); + + logger.trace( "Trying write {} in {} bytes", path, safeBytes.length ); + + context.getFileHandler().write( + path, + new ByteArrayInputStream( safeBytes ) + ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java new file mode 100644 index 000000000..1c1ca7679 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java @@ -0,0 +1,66 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import static org.tizen.common.util.StringUtil.NULL_STRING; + +import java.text.MessageFormat; + +/** + * AbstractMessagePolicy. + * + * Abstract class for {@link MessagePolicy} + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +abstract public class +AbstractMessagePolicy +implements MessagePolicy +{ + + /** + * Provide common formatting rule + * + * @param format message format + * @param args message arguments + * + * @return formatted message + */ + protected + String + format( + final String format, + final Object... args + ) + { + if ( null == format ) + { + return NULL_STRING; + } + return MessageFormat.format( format, args ); + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java new file mode 100644 index 000000000..25b12a551 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java @@ -0,0 +1,73 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import org.tizen.common.core.command.Policy; + +/** + * AbstractPolicy. + * + * Abstract class for {@link Policy} + * + * All policy must have name and can't change it + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +abstract public class +AbstractPolicy +implements Policy +{ + + /** + * Policy name + */ + protected final String name; + + /** + * Constructor with policy name + * + * @param name poclicy name + * + * @see Policy + */ + public + AbstractPolicy( + final String name + ) + { + this.name = name; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Policy#getName() + */ + @Override + public + String + getName() + { + return this.name; + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java new file mode 100644 index 000000000..d70487f09 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java @@ -0,0 +1,76 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + + +/** + * FilePolicy. + * + * File handling policy + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public enum +FilePolicy +{ + /** + * <p> + * Stop process. + * + * Throw exception + * </p> + */ + STOP_PROCESS, + + /** + * <p> + * Skip process. + * + * Don't throw exception + * </p> + */ + SKIP, + + /** + * <p> + * overwwrite when already exist + * </p> + */ + OVERWRITE, + + /** + * <p> + * Make directory when directory doesn't exist + * </p> + */ + MAKE_DIR, + + /** + * <p> + * Make file when file doesn't exist + * </p> + */ + MAKE_FILE +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java new file mode 100644 index 000000000..379c601c5 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java @@ -0,0 +1,146 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.core.command.Prompter; + +/** + * FilePolicy. + * + * File handling policy + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +MessagePolicy +{ + /** + * Print out message + * + * @param prompter {@link Prompter} + * @param format message format + * @param args message arguments + */ + void + print( + final Prompter prompter, + final String format, + final Object... args + ); + + /** + * Print out error message + * @param prompter {@link Prompter} + * @param format message format + * @param args message arguments + */ + void + error( + final Prompter prompter, + final String format, + final Object... args + ); + + /** + * {@link MessagePolicy} to print out using logger + * + * FIXME caller fqcn is constants + */ + MessagePolicy LOGGING = new AbstractMessagePolicy() + { + /** + * Logger to use for message printing + */ + protected final Logger logger = + LoggerFactory.getLogger( getClass() ); + + /* (non-Javadoc) + * @see org.tizen.common.core.command.policy.MessagePolicy#print(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[]) + */ + @Override + public + void + print( + final Prompter prompter, + final String format, + final Object... args + ) + { + logger.debug( format( format, args ) ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.policy.MessagePolicy#error(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[]) + */ + @Override + public void error( + final Prompter prompter, + final String format, + final Object... args + ) + { + logger.error( format( format, args ) ); + } + }; + + /** + * {@link MessagePolicy} to print out using {@link Prompter} + */ + MessagePolicy PROMPTER = new AbstractMessagePolicy() + { + + /* (non-Javadoc) + * @see org.tizen.common.core.command.policy.MessagePolicy#print(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[]) + */ + @Override + public + void + print( + final Prompter prompter, + final String format, + final Object... args + ) + { + prompter.notify( format( format, args ) ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.policy.MessagePolicy#error(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[]) + */ + @Override + public void error( + final Prompter prompter, + final String format, + final Object... args + ) + { + prompter.error( format( format, args ) ); + + } + }; + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java new file mode 100644 index 000000000..df6e4821f --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java @@ -0,0 +1,60 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.core.command.policy; + +import org.tizen.common.core.command.prompter.Option; + +/** + * OptionPolicy + * This policy returns options which are needed for Prompt#interact(final String question, final Option... options). + * @See Command, Prompter + * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) + */ + +public class OptionPolicy { + + protected Option[] options; + + /** + * <p> + * Constructor with <code>options</code> + * </p> + * + * @param options options which this policy will return. + */ + public OptionPolicy(Option... options) { + this.options = options; + } + + /** + * Returns options this policy has. + * + * @return return options. + */ + public Option[] getOptions() { + return options; + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java b/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java new file mode 100644 index 000000000..0308d6ac6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java @@ -0,0 +1,294 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import java.util.HashMap; + +import org.tizen.common.core.command.Policy; +import org.tizen.common.util.StringUtil; + + +/** + * <p> + * PolicyRegistry. + * + * Registry for {@link Policy} + * + * {@link Policy} is stored in tree-like structure + * + * A node has {@link Policy} or doesn't + * + * A node has multiple child nodes + * + * Policy's location is made a decision by its name + * + * name is composed of subname and separator( "<b>.</b>" ) + * + * example for name is following + * <ul> + * <li>invalid.input.format.file</li> + * <li>nonexist.input.file</li> + * <li>exist.output.file</li> + * </ul> + * </p> + * @author bylee + * + */ +public class PolicyRegistry +{ + /** + * Node. + * + * Node for tree structure + * + * @author bylee + * + */ + class Node + { + + /** + * {@link Policy} stored in node + */ + protected Policy policy; + + /** + * Default constructor + */ + public Node() + { + } + + /** + * Constructor with {@link Policy} + * + * @param policy {@link Policy} to store + */ + public Node( + final Policy policy + ) + { + this.policy = policy; + } + + protected final HashMap<String, Node> name2child = + new HashMap<String, PolicyRegistry.Node>(); + + /** + * Rerturn {@link Policy} to be stored + * + * @return policy to be stored + */ + public Policy getPolicy() + { + return this.policy; + } + + /** + * Set policy + * + * @param policy {@link Policy} to store + */ + public void setPolicy( + final Policy policy + ) + { + this.policy = policy; + } + + + /** + * Get child node with <code>name</code> in this node + * + * @param name node's name + * + * @return child node with <code>name</code> + */ + public Node getChild( + final String name + ) + { + return name2child.get( name ); + } + + /** + * Add <code>node</code> with <code>name</code> as child + * + * @param name node name + * @param node node to add + */ + public void addChild( final String name, Node node ) + { + name2child.put( name, node ); + } + } + + /** + * No-operation policy. Missing object pattern + */ + protected Policy noOp = new AbstractPolicy( "" ) + { + /* (non-Javadoc) + * @see org.tizen.common.Adaptable#adapt(java.lang.Class) + */ + @Override + public <T> T adapt( final Class<T> clazz ) + { + return null; + } + }; + + /** + * Root node( in tree structure) + */ + protected Node root = new Node(); + + /** + * Constructor with {@link Policy}s + * + * @param policies {@link Policy}s to add + * + * @see #register(Policy) + */ + public + PolicyRegistry( + final Policy... policies + ) + { + if ( null == policies ) + { + return ; + } + + register( policies ); + } + + /** + * Add <code>policies</code> to registry + * + * @param policies {@link Policy}s to add + */ + public void + register( + final Policy... policies + ) + { + for ( final Policy policy : policies ) + { + final String name = policy.getName(); + + final Node node = createNode( name ); + + if ( null != node.getPolicy() ) + { + throw new IllegalArgumentException( "Policy is duplicated" ); + } + + node.setPolicy( policy ); + } + + } + + /** + * Create node with <code>path</code> in tree + * + * @param path node path from root in tree + * + * @return {@link Node} to be specified with <code>path</code> + */ + public Node createNode( final String path ) + { + final String[] fragments = StringUtil.split( path, "." ); + + Node iter = root; + + for ( int i = 0, n = fragments.length ; i < n ; ++i ) + { + Node child = iter.getChild( fragments[i] ); + if ( null == child ) + { + child = new Node(); + iter.addChild( fragments[i], child ); + } + + iter = child; + } + + return iter; + } + + /** + * Return {@link Policy} from tree with <code>path</code> + * + * Return ancestor node's policy unless matching exactly + * + * @param path + * + * @return {@link Policy} + */ + public Policy + getPolicy( final String path ) + { + if ( StringUtil.isEmpty( path ) ) + { + return noOp; + } + final String[] fragments = StringUtil.split( path, "." ); + + Node iter = root; + + Policy policy = null; + + for ( int i = 0, n = fragments.length ; i < n ; ++i ) + { + if ( null != iter.getPolicy() ) + { + policy = iter.getPolicy(); + } + + Node child = iter.getChild( fragments[i] ); + if ( null == child ) + { + return policy; + } + iter = child; + } + + if ( null == iter.getPolicy() ) + { + return policy; + } + return iter.getPolicy(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() + { + return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java new file mode 100644 index 000000000..d0f7638cd --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java @@ -0,0 +1,49 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import org.tizen.common.core.command.Policy; + +public class SimplePolicy +implements Policy { + + protected String name; + + public SimplePolicy( final String name ) + { + this.name = name; + } + @Override + public <T> T adapt(Class<T> clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + return name; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java new file mode 100644 index 000000000..f16f9c712 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java @@ -0,0 +1,113 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Ho Namkoong <ho.namkoong@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.policy; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.HashMap; +import java.util.Map; + +import org.tizen.common.core.command.CommandCancelException; +import org.tizen.common.util.log.Logger; + +/** + * UncaughtExceptionHandlingPolicy. + * + * Exception handling policy + * Singleton class implemented using enum + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + */ +public enum UncaughtExceptionHandlingPolicy + implements + UncaughtExceptionHandler { + + /** + * singleton instance. + */ + INSTANCE(); + + /** + * map which stores handler (value) according to the throwable class name (name). + */ + private final Map<String, UncaughtExceptionHandler> repository = new HashMap<String, UncaughtExceptionHandler>(); + + /** + * get handler from repository, and handle exception. + * If appropriate repository is not found, + * it searches for handler which handles superclass of target exception. + * + * @param t current thread + * @param e exception which should be handled + * @since 1.5 + */ + @Override + public void uncaughtException(Thread t, Throwable e) { + + UncaughtExceptionHandler handler = null; + Class<? extends Object> throwableClass = e.getClass(); + + do { + handler = repository.get(throwableClass.getCanonicalName()); + if(handler != null) { + handler.uncaughtException(t, e); + return; + } + + throwableClass = throwableClass.getSuperclass(); + } while (!throwableClass.getCanonicalName().equals(Object.class.getCanonicalName())); + + throw new IllegalStateException(e); + } + + private UncaughtExceptionHandlingPolicy() { + installUncaughtExceptionHandlers(); + } + + private void installUncaughtExceptionHandlers() { + + //Install OperationCancelException Handler + this.putHandler(CommandCancelException.class.getCanonicalName(), new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + if(e instanceof CommandCancelException) { + throw (CommandCancelException)e; + } + else { + throw new IllegalStateException(); + } + } + }); + } + + private void putHandler(String throwableName, UncaughtExceptionHandler handler) { + if(repository.containsKey(throwableName)) { + if(!repository.get(throwableName).equals(handler)) { + Logger.error("Handlers are duplicate assigned with one key: " + throwableName); + } + return; + } + repository.put(throwableName, handler); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java new file mode 100644 index 000000000..d60b177d7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java @@ -0,0 +1,181 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import static org.tizen.common.util.StringUtil.isEmpty; +import static org.tizen.common.util.StringUtil.trim; + +import org.tizen.common.util.ObjectUtil; + +/** + * <p> + * AbstractOption. + * + * Abstract(common) class for option + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +AbstractOption +implements Option +{ + /** + * <p> + * Option name + * + * It is printed out + * </p> + */ + protected final String name; + + /** + * Flag if user input is handled as abbreviation + */ + protected final boolean bPermitAbbreviation; + + /** + * Flag if this option is default( choice when user doesn't select option ) + */ + protected final boolean bDefault; + + /** + * Constructor with choice name, default flag and abbreviation flag + * + * @param name choice name + * @param bDefault default flag + * @param bPermitAbbreviation abbreviation flag + */ + public + AbstractOption( + final String name, + final boolean bDefault, + final boolean bPermitAbbreviation + ) + { + this.name = trim( name ); + + this.bDefault = bDefault; + + this.bPermitAbbreviation = bPermitAbbreviation; + } + + /** + * Return option name + * + * @return option name + */ + public String getName() + { + return this.name; + } + + /** + * Return whether this choice is default {@link ChoiceOption} + * + * @return boolean value if this choice is default + */ + public boolean isDefault() + { + return this.bDefault; + } + + /** + * Return whether user input, <code>value</code> is match option + * + * @param value user input + * + * @return boolean value If matching + */ + public + boolean + isMatch( + final String value + ) + { + if ( name.equalsIgnoreCase( trim( value ) ) ) + { + return true; + } + + if ( isEmpty( value ) ) + { + return false; + } + if ( bPermitAbbreviation ) + { + return name.substring( 0, 1 ).equalsIgnoreCase( value.substring( 0, 1 ) ); + } + + return false; + + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public + int + hashCode() + { + return name.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public + boolean + equals( + final Object obj + ) + { + if ( !( obj instanceof ChoiceOption ) ) + { + return false; + } + final ChoiceOption other = (ChoiceOption) obj; + return ObjectUtil.equals( this.name, other.name ); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + if ( isDefault() ) + { + return "[" + name + "]"; + } + return name; + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java new file mode 100644 index 000000000..701a9772c --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java @@ -0,0 +1,86 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.core.command.Prompter; + +/** + * AbstractPrompter. + * + * Abstract class for sub class for {@link Prompter} + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +AbstractPrompter +{ + + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + protected + void + checkOptions( ChoiceOption[] options ) + { + if ( null == options ) + { + throw new NullPointerException(); + } + + final HashSet<Option> reducedOptions = new LinkedHashSet<Option>(); + Option defaultOption = null; + final ArrayList<String> optionNames = new ArrayList<String>(); + for ( final Option option : options ) + { + if ( reducedOptions.contains( option ) ) + { + throw new IllegalArgumentException( + "Question can't have duplicated choice(s) :" + option + ); + } + optionNames.add( option.getName() ); + reducedOptions.add( option ); + if ( option.isDefault() ) + { + if ( null != defaultOption ) + { + throw new IllegalArgumentException( + "Question must have only one default choice" + ); + } + + defaultOption = option; + } + } + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java new file mode 100644 index 000000000..267941b5f --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java @@ -0,0 +1,95 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import static org.tizen.common.util.StringUtil.hasText; + +import org.tizen.common.util.Assert; + +/** + * <p> + * Option. + * + * Option to choice + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +ChoiceOption +extends AbstractOption +{ + /** + * Constructor with choice name + * + * @param name choice name + * + * #see {@link #Option(String, boolean)} + */ + public + ChoiceOption( + final String name + ) + { + this( name, false ); + } + + /** + * Constructor with choice name and default flag + * + * @param name choice name + * @param bDefault default flag + * + * @see #Option(String, boolean, boolean) + */ + public + ChoiceOption( + final String name, + final boolean bDefault + ) + { + this( name, bDefault, true ); + } + + /** + * Constructor with choice name, default flag and abbreviation flag + * + * @param name choice name + * @param bDefault default flag + * @param bPermitAbbreviation abbreviation flag + */ + public + ChoiceOption( + final String name, + final boolean bDefault, + final boolean bPermitAbbreviation + ) + { + super( name, bDefault, bPermitAbbreviation ); + Assert.isTrue( hasText( name ) ); + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java new file mode 100644 index 000000000..cb4f3e6d3 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java @@ -0,0 +1,201 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import java.util.HashMap; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.Platform; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.core.command.Prompter; +import org.tizen.common.util.ObjectUtil; +import org.tizen.common.util.StringUtil; + +/** + * <p> + * EclipsePrompter. + * + * Context aware prompter using extension + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +EclipsePrompter +implements Prompter +{ + protected static final String EP_ID = "org.tizen.common.prompter"; + + protected static final String ATTR_SCOPE = "scope"; + + protected static final String ATTR_CLASS = "class"; + + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Default prompter + */ + protected final Prompter defaultPrompter; + + protected final HashMap<String, Prompter> name2prompter; + + /** + * Constructor with default prompter + * + * @param defaultPrompter {@link Prompter} + */ + public EclipsePrompter( + final Prompter defaultPrompter + ) + { + this.defaultPrompter = defaultPrompter; + this.name2prompter = new HashMap<String, Prompter>(); + } + + protected Prompter + getPrompter() + { + final StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); + + final IExtensionRegistry registry = Platform.getExtensionRegistry(); + final IExtensionPoint ep = registry.getExtensionPoint( EP_ID ); + final IExtension[] exts = ep.getExtensions(); + + for ( final StackTraceElement stack : stacks ) + { + final String className = stack.getClassName(); + + for ( final IExtension ext : exts ) + { + final IConfigurationElement[] configs = ext.getConfigurationElements(); + for ( IConfigurationElement config : configs ) + { + final String scope = config.getAttribute( ATTR_SCOPE ); + if ( StringUtil.isEmpty( scope ) ) + { + continue; + } + + if ( !ObjectUtil.equals( className, scope ) ) + { + continue; + } + + try { + return (Prompter) config.createExecutableExtension( ATTR_CLASS ); + } catch ( CoreException e ) + { + logger.error( "Can't create prompter :" + config.getAttribute( ATTR_CLASS ) ); + return defaultPrompter; + } + } + } + } + + return defaultPrompter; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, org.tizen.common.core.command.prompter.Option[]) + */ + @Override + public Option interact( + final String question, + final Option... options + ) + { + final Prompter prompter = getPrompter(); + return prompter.interact(question, options); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#password(java.lang.String) + */ + @Override + public + char[] password( + final String message + ) + { + final Prompter prompter = getPrompter(); + return prompter.password(message); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#error(java.lang.String) + */ + @Override + public + void + error( + final String message + ) + { + final Prompter prompter = getPrompter(); + prompter.error(message); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#notify(java.lang.String) + */ + @Override + public + void + notify( + final String message + ) + { + final Prompter prompter = getPrompter(); + prompter.notify(message); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#cancel() + */ + @Override + public + void + cancel() + { + final Prompter prompter = getPrompter(); + prompter.cancel(); + } + + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() + { + return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java new file mode 100644 index 000000000..003b35bd8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java @@ -0,0 +1,149 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import static org.tizen.common.util.StringUtil.hasText; + +import org.tizen.common.util.Assert; + +/** + * <p> + * GenericOption. + * + * {@link ChoiceOption} for general input + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +GenericOption +extends AbstractOption +{ + + /** + * User input + */ + protected String answer; + + /** + * Default constructor + */ + public + GenericOption() + { + super( "", false, false ); + } + + /** + * Constructor with choice name + * + * @param name choice name + * + * #see {@link #Option(String, boolean)} + */ + public + GenericOption(final String name) + { + super( name, false, false ); + this.answer = name; + } + + /** + * Constructor with choice name and default flag + * + * @param name choice name + * @param bDefault default flag + * + * @see #Option(String, boolean, boolean) + */ + public + GenericOption ( + final String name, + final boolean bDefault + ) + { + super( name, bDefault, false ); + this.answer = name; + } + + /** + * Constructor with choice name, default flag and abbreviation flag + * + * @param name choice name + * @param bDefault default flag + * @param bPermitAbbreviation abbreviation flag + */ + public + GenericOption ( + final String name, + final boolean bDefault, + final boolean bPermitAbbreviation + ) + { + super( name, bDefault, bPermitAbbreviation ); + Assert.isTrue( hasText( name ) ); + this.answer = name; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.prompter.AbstractOption#isMatch(java.lang.String) + */ + @Override + public + boolean + isMatch( + final String value + ) + { + this.answer = value; + return true; + } + + /** + * Return user input + * + * @return user input + */ + public String + getAnswer() + { + return this.answer; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + if ( isDefault() ) + { + return "[" + this.answer + "]"; + } + return this.answer; + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java new file mode 100644 index 000000000..c202a35b6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java @@ -0,0 +1,129 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import org.tizen.common.core.command.Prompter; + +/** + * <p> + * NopPrompter. + * + * No-Operation Prompter doesn't interact with human + * + * It is used for batch process or test + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +NopPrompter +extends AbstractPrompter +implements Prompter +{ + + protected char[] password; + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, int, org.tizen.common.core.command.prompter.Option[]) + */ + public + Option + interact( + final String question, + final Option... options + ) + { + for ( Option option : options ) + { + if ( option.isDefault() ) + { + return option; + } + } + throw new IllegalArgumentException(); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#notify(java.lang.String, java.lang.Object[]) + */ + @Override + public + void + notify( + final String message + ) + { + logger.info( "Notification >>> {}", message ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#cancel() + */ + @Override + public void cancel() + { + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#password(java.lang.String) + */ + @Override + public + char[] password( + final String message + ) + { + return password; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#error(java.lang.String, java.lang.Object[]) + */ + @Override + public + void + error( + final String message + ) + { + logger.error( "Error >>> {}", message ); + } + + /** + * Set password + * + * @param password password to be provided automatically + */ + public + void + setPassword( + final char[] password + ) + { + this.password = password; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java new file mode 100644 index 000000000..c2c624ce4 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java @@ -0,0 +1,11 @@ +package org.tizen.common.core.command.prompter; + +public interface Option +{ + String getName(); + + boolean isDefault(); + + boolean isMatch( final String value ); + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java new file mode 100644 index 000000000..dc78fe7de --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java @@ -0,0 +1,124 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Ho Namkoong <ho.namkoong@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ + +package org.tizen.common.core.command.prompter; + +public abstract class RunableOption implements Option{ + + /** + * Arguments which will be used in run. + */ + private Object[] args; + + /** + * if true, remaning selection is following this option + * For example, if you select ignore all or overwrite all when deuplicate files are found, then this flag becomes true. + */ + private boolean allFlag = false; + + /** + * name of this option + */ + private String name; + + /** + * Constructor with name + * + * @param name name of this operation + */ + public RunableOption(String name) { + this.name = name; + this.args = null; + } + + /** + * Constructor with name and arguments + * + * @param name name of this operation + * @param args arguments of this operation + */ + public RunableOption(String name, Object... args) { + this.name = name; + this.args = args; + } + + /** + * Set arguments + * + * @param args arguments of this operation + */ + public void setArgument(Object... args) { + this.args = args; + } + + /** + * Set all flag + * + * @param allFlag all flag of this operation + */ + protected void setAllFlag(boolean allFlag) { + this.allFlag = allFlag; + } + + /** + * return all flag + * + * @return return true if all flag is true, else return false + */ + public boolean isAllFlag() { + return allFlag; + } + + /** + * return name + * + * @return return name of this operation + */ + @Override + public String getName() { + return name; + } + + /** + * Check if name of this operation and value are matched. + * + * @arg value value which is compared with name of this operation + * @return return true if matched, else return false. + */ + @Override + public boolean isMatch(String value) { + if(this.getName().equals(value)) { + return true; + } + return false; + } + + protected abstract void runWithArgument(Object... args) throws Exception; + + public void run() throws Exception { + this.runWithArgument(args); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java new file mode 100755 index 000000000..ca29bffc6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java @@ -0,0 +1,233 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.prompter; + +import static org.tizen.common.util.SWTUtil.asyncExec; +import static org.tizen.common.util.SWTUtil.exec; +import static org.tizen.common.util.SWTUtil.getActiveShell; +import static org.tizen.common.util.SWTUtil.syncExec; +import static org.tizen.common.util.StringUtil.trim; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.tizen.common.core.command.Prompter; +import org.tizen.common.ui.dialog.PasswordInputDialog; +import org.tizen.common.util.NotificationType; +import org.tizen.common.util.NotifierDialog; +import org.tizen.common.util.SWTRunner; + +/** + * <p> + * SWTPrompter. + * + * {@link Prompter} in SWT environment + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +SWTPrompter +extends AbstractPrompter +implements Prompter +{ + + /** + * Create dialog for user interaction + * + * @param question message for dialog + * @param optionNames option names for dialog + * @param defaultOptionIndex initial selection for option + * + * @return {@link Dialog} for user selection + */ + protected + Dialog + createDialog( + final String question, + final String[] optionNames, + final int defaultOptionIndex + ) + { + return new MessageDialog( + getActiveShell(), + "Question", + null, + question, + MessageDialog.QUESTION, + optionNames, + defaultOptionIndex + ) + { + protected void buttonPressed( int buttonId ) + { + setReturnCode( buttonId ); + close(); + } + }; + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, org.tizen.common.core.command.prompter.Option[]) + */ + @Override + public + Option + interact( + final String question, + final Option... options + ) + { + final HashSet<Option> reducedOptions = new LinkedHashSet<Option>(); + Option defaultOption = null; + final ArrayList<String> optionNames = new ArrayList<String>(); + for ( final Option option : options ) + { + if ( reducedOptions.contains( option ) ) + { + throw new IllegalArgumentException( + "Question can't have duplicated choice(s) :" + option + ); + } + optionNames.add( option.getName() ); + reducedOptions.add( option ); + if ( option.isDefault() ) + { + if ( null != defaultOption ) + { + throw new IllegalArgumentException( + "Question must have only one default choice" + ); + } + + defaultOption = option; + } + } + final int defaultIndex = optionNames.indexOf( defaultOption.getName() ); + + return exec( new SWTRunner<Option>() + { + /* (non-Javadoc) + * @see org.tizen.common.util.SWTRunner#process() + */ + public Option process() { + final Dialog dialog = createDialog( question, optionNames.toArray( new String[0] ), defaultIndex ); + dialog.open(); + return options[dialog.getReturnCode()]; + } + } ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#notify(java.lang.String, java.lang.Object[]) + */ + @Override + public void + notify( + final String message + ) + { + asyncExec( new Runnable() { + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + NotifierDialog.notify( "Notify", message, NotificationType.INFO ); + } + } ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#cancel() + */ + @Override + public void cancel() { + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#password(java.lang.String) + */ + @Override + public + char[] password( + final String message + ) + { + return exec( new SWTRunner<char[]>() + { + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public char[] process() + { + final PasswordInputDialog dialog = + new PasswordInputDialog( "Password Input Dialog", message ); + + dialog.open(); + + if ( IDialogConstants.OK_ID != dialog.getReturnCode() ) + { + return null; + } + + return trim( dialog.getValue() ).toCharArray(); + } + } ); + + + + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.Prompter#error(java.lang.String, java.lang.Object[]) + */ + @Override + public + void + error( + final String message + ) + { + syncExec( new Runnable() { + + /* (non-Javadoc) + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + MessageDialog.openError( getActiveShell(), "Error", message ); + } + } ); + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java new file mode 100644 index 000000000..e86d38d07 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java @@ -0,0 +1,65 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.Assert; +import org.tizen.sdblib.IDevice; + +public class DevicesSdbCommand +extends SdbHandlingCommand +{ + protected SmartDevelopmentBridgeManager createBridge() + { + return new SmartDevelopmentBridgeManager(); + } + + @Override + public void run( final Executor executor, ExecutionContext context) + { + SmartDevelopmentBridgeManager bridge = createBridge(); + Assert.notNull( bridge ); + + IDevice devices[] = bridge.getDevices(); + String result = new String(); + for ( IDevice device : devices ) + { + result += device.toString() + System.getProperty("line.separator"); + } + setResult( result ); + + context.getPrompter().notify( getResult() ); + } + + @Override + public void undo(final Executor executor, ExecutionContext context) throws Exception + { + // TODO Auto-generated method stub + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java new file mode 100644 index 000000000..f4bfb887d --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java @@ -0,0 +1,54 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; + +public class DlogSdbCommand +extends ShellSdbCommand +{ + protected String DLOG_COMMAND = "dlogutil"; + + public void setFilter(String filter) { + this.DLOG_COMMAND = "dlogutil "+filter; + } + + @Override + public void run(Executor executor, ExecutionContext context) + throws Exception { + setCommand( this.DLOG_COMMAND ); + super.run( executor, context ); + } + + @Override + public void undo(Executor executor, ExecutionContext context) + throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java new file mode 100644 index 000000000..11540d85b --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java @@ -0,0 +1,70 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.Assert; +import org.tizen.sdblib.IDevice; + +public class ForwardSdbCommand +extends SdbDevicesHandlingCommand +{ + private int localPort; + private int remotePort; + + public ForwardSdbCommand(int localPort, int remotePort) { + this.localPort = localPort; + this.remotePort = remotePort; + } + + @Override + public void run(final Executor executor, ExecutionContext context) throws InterruptedException { + IDevice device = getDevice(); + Assert.notNull( device ); + + try { + device.createForward( localPort, remotePort ); + } catch (Exception e) { + // TODO Message fix need + context.getPrompter().notify( "forward socket connections error" ); + } + } + + @Override + public void undo(Executor executor, ExecutionContext context) + throws Exception { + IDevice device = getDevice(); + Assert.notNull( device ); + + try { + device.removeForward( localPort, remotePort ); + } catch (Exception e) { + // TODO Message fix need + context.getPrompter().notify( "remove forward socket connections error" ); + } + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java new file mode 100644 index 000000000..925729877 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java @@ -0,0 +1,87 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import java.io.IOException; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.Assert; +import org.tizen.sdblib.IDevice; +import org.tizen.sdblib.SdbCommandRejectedException; +import org.tizen.sdblib.SyncService; +import org.tizen.sdblib.SyncService.ISyncProgressMonitor; +import org.tizen.sdblib.SyncService.SyncResult; +import org.tizen.sdblib.TimeoutException; + +public class PullSdbCommand +extends SdbDevicesHandlingCommand +{ + protected String remotePath; + protected String localPath; + + public PullSdbCommand(String remotePath, String localPath) + { + this.remotePath = remotePath; + this.localPath = localPath; + } + + protected SyncService getSyncService() throws TimeoutException, SdbCommandRejectedException, IOException + { + return device.getSyncService(); + } + + protected ISyncProgressMonitor getProgressMonitor() { + return SyncService.getNullProgressMonitor(); + } + + @Override + public void run(final Executor executor, ExecutionContext context) + throws Exception + { + IDevice device = getDevice(); + Assert.notNull( device ); + + try + { + SyncService service = getSyncService(); + SyncResult syncSuccess = + service.pullFile( remotePath, localPath, getProgressMonitor() ); + if ( syncSuccess.getCode() != SyncService.RESULT_OK ) { + // TODO Message fix need + context.getPrompter().notify( "transfer error" ); + } + } catch (Exception e) { + throw new IllegalStateException( e ); + } + } + + @Override + public void undo(final Executor executor, ExecutionContext context) throws Exception { + // TODO Auto-generated method stub + + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java new file mode 100644 index 000000000..46db4c404 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java @@ -0,0 +1,93 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import java.io.IOException; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.Assert; +import org.tizen.common.util.FilenameUtil; +import org.tizen.sdblib.IDevice; +import org.tizen.sdblib.SdbCommandRejectedException; +import org.tizen.sdblib.SyncService; +import org.tizen.sdblib.SyncService.ISyncProgressMonitor; +import org.tizen.sdblib.SyncService.SyncResult; +import org.tizen.sdblib.TimeoutException; + +public class PushSdbCommand +extends SdbDevicesHandlingCommand +{ + protected String localPath; + protected String remotePath; + + public PushSdbCommand(String localPath, String remotePath) + { + this.localPath = localPath; + this.remotePath = remotePath; + } + + protected SyncService getSyncService() throws TimeoutException, SdbCommandRejectedException, IOException + { + return device.getSyncService(); + } + + protected ISyncProgressMonitor getProgressMonitor() { + return SyncService.getNullProgressMonitor(); + } + + @Override + public void run(final Executor executor, ExecutionContext context) + throws Exception + { + IDevice device = getDevice(); + Assert.notNull( device ); + + try + { + SyncService service = getSyncService(); + SyncResult syncSuccess = + service.pushFile( localPath, remotePath, getProgressMonitor() ); + String name = FilenameUtil.getFilename( localPath ); + if ( syncSuccess.getCode() != SyncService.RESULT_OK ) { + setResult( "failed" ); + context.getPrompter().notify( name + " file transfer failed" ); + return ; + } + setResult( "success" ); + context.getPrompter().notify( name + " file transfer success" ); + } catch (Exception e) { + throw new IllegalStateException( e ); + } + } + + @Override + public void undo(final Executor executor, ExecutionContext context) throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/model/DefaultTreeModel.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbDevicesHandlingCommand.java index 687c3089a..95230fce0 100644 --- a/org.tizen.common/src/org/tizen/common/model/DefaultTreeModel.java +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbDevicesHandlingCommand.java @@ -1,44 +1,45 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-
-
-public class DefaultTreeModel extends AbstractTreeModel {
-
- public DefaultTreeModel(ITreeVO source){
- super(source);
- }
-
- public String getSourceName() {
- String str = this.source.getClass().getSimpleName();
- if(str.endsWith("VO")) //$NON-NLS-1$
- str = str.substring(0,str.length()-2);
- return str;
- }
-}
-
-
+/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.sdblib.IDevice; + +public abstract class +SdbDevicesHandlingCommand +extends SdbHandlingCommand +{ + protected IDevice device; + + public void setDevice(IDevice device) + { + this.device = device; + } + + public IDevice getDevice() + { + return this.device; + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java new file mode 100644 index 000000000..6c98a729a --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java @@ -0,0 +1,60 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.common.core.command.Command; + +public abstract class +SdbHandlingCommand +implements Command<String> +{ + protected StringBuffer result; + + public void clearResult() { + if ( this.result == null ) { + this.result = new StringBuffer(); + } else { + this.result.delete( 0, result.capacity() ); + this.result.setLength( 0 ); + } + } + + public String getResult() + { + if ( this.result == null ) { + return null; + } + return this.result.toString(); + } + + public void setResult(String result) + { + if ( this.result == null ) { + this.result = new StringBuffer(); + } + this.result.append( result ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java new file mode 100644 index 000000000..5efc22f53 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java @@ -0,0 +1,142 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.util.Assert; +import org.tizen.sdblib.IDevice; +import org.tizen.sdblib.MultiLineReceiver; + +/** + * <p> + * ShellSdbCommand. + * + * Command to run shell in target + * </p> + * + * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core) + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class ShellSdbCommand +extends SdbDevicesHandlingCommand +{ + private String command; + private static int DEFAULT_TIME = 90; + + /** + * Wait for shell command completion + */ + private int time; + + /** + * Get wait for shell command completion time + * + * @return time value + */ + public int getTime() { + return time; + } + + /** + * Set wait for shell command completion time + * + * @param time value + */ + public void setTime(int time) { + this.time = time <= 0 ? DEFAULT_TIME : time; + } + + /** + * Constructor, default command is empty so if using this constructor then must call setCommand + */ + public ShellSdbCommand() { + this.time = DEFAULT_TIME; + } + + /** + * Constructor with command, command is running in target device. + * + * @param command + */ + public ShellSdbCommand(String command) { + this.command = command; + this.time = DEFAULT_TIME; + } + + /** + * Get command, command is running in target device + * + * @return command + */ + public String getCommand() { + return command; + } + + /** + * Set command, command is running in target device + * + * @param command + */ + public void setCommand(String command) { + this.command = command; + } + + /** + * Create MultiLineReceiver, MultiLineReceiver's processNewLines method save command running result + * + * @return MultiLineReceiver + */ + public MultiLineReceiver createMultiLineReceiver() { + return new MultiLineReceiver() { + @Override + public void processNewLines(String[] lines) { + for( String content: lines ) { + setResult( content+System.getProperty( "line.separator" ) ); + } + } + }; + } + + @Override + public void run(Executor executor, ExecutionContext context) + throws Exception { + IDevice device = getDevice(); + Assert.notNull( device ); + Assert.notNull( command ); + + clearResult(); + device.executeShellCommand( command, createMultiLineReceiver(), getTime()*1000 ); + } + + @Override + public void undo(Executor executor, ExecutionContext context) + throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java new file mode 100644 index 000000000..66a5bb9f4 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java @@ -0,0 +1,93 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* GyeongSeok Seo <gyeongseok.seo@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.core.command.sdb; + +import org.tizen.sdblib.IDevice; +import org.tizen.sdblib.SmartDevelopmentBridge; + +/** + * <p> + * SmartDevelopmentBridgeManager. + * + * class for delegate SmartDevelopmentBridge. + * + * </p> + * + * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core) + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class SmartDevelopmentBridgeManager +{ + private SmartDevelopmentBridge impl = SmartDevelopmentBridge.getBridge(); + + public boolean equals(Object obj) { + return impl.equals(obj); + } + + public int getConnectionAttemptCount() { + return impl.getConnectionAttemptCount(); + } + + public IDevice[] getDevices() { + return impl.getDevices(); + } + + public int getRestartAttemptCount() { + return impl.getRestartAttemptCount(); + } + + public String getSdbOsLocation() { + return impl.getSdbOsLocation(); + } + + public boolean hasInitialDeviceList() { + return impl.hasInitialDeviceList(); + } + + public int hashCode() { + return impl.hashCode(); + } + + public boolean isConnected() { + return impl.isConnected(); + } + + public boolean restart() { + return impl.restart(); + } + + public String toString() { + return impl.toString(); + } + + public void disconnectBridge() { + impl.disconnectBridge(); + } + + public void terminate() { + impl.terminate(); + } +} diff --git a/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java b/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java new file mode 100644 index 000000000..639349f30 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java @@ -0,0 +1,196 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.core.command.zip; + +import static org.tizen.common.core.command.Policy.EXIST_OUT_WGT; +import static org.tizen.common.core.command.Policy.NONEXIST_IN_DIRECTORY; +import static org.tizen.common.util.FilenameUtil.getRelativePath; +import static org.tizen.common.util.IOUtil.tryClose; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Queue; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.tizen.common.core.command.ExecutionContext; +import org.tizen.common.core.command.Executor; +import org.tizen.common.core.command.Policy; +import org.tizen.common.core.command.file.FileHandlingCommand; +import org.tizen.common.core.command.policy.FilePolicy; +import org.tizen.common.core.command.policy.MessagePolicy; +import org.tizen.common.file.FileHandler; +import org.tizen.common.file.FileHandler.Attribute; +import org.tizen.common.file.FileHandler.Type; +import org.tizen.common.util.Assert; +import org.tizen.common.util.FilenameUtil; +import org.tizen.common.util.IOUtil; + +/** + * <p> + * ZipCommand. + * + * Command to make zip archive + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +ZipCommand +extends FileHandlingCommand<Object> +{ + /** + * Directory to zip + */ + protected final String baseDir; + + /** + * Constructor with base dir and target file name + * + * @param baseDir base directory path + * @param target target file name + */ + public + ZipCommand( + final String baseDir, + final String target + ) + { + this.baseDir = baseDir; + setPath( target ); + } + + /* (non-Javadoc) + * @see org.tizen.common.core.command.file.FileHandlingCommand#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext) + */ + @Override + public + void + run( + final Executor executor, + final ExecutionContext context + ) + throws IOException, InterruptedException + { + final FileHandler handler = context.getFileHandler(); + Assert.notNull( handler ); + + if ( !handler.is( baseDir, Attribute.EXISTS ) ) + { + final Policy policy = context.getPolicy( NONEXIST_IN_DIRECTORY ); + + final MessagePolicy messagePolicy = policy.adapt( MessagePolicy.class ); + + messagePolicy.print( context.getPrompter(), "{0} doesn't exist", baseDir ); + return ; + } + + if ( handler.is( path, Attribute.EXISTS ) ) + { + final Policy policy = context.getPolicy( EXIST_OUT_WGT ); + + final MessagePolicy messagePolicy = policy.adapt( MessagePolicy.class ); + messagePolicy.print( context.getPrompter(), "Widget already exists" ); + + final FilePolicy filePolicy = policy.adapt( FilePolicy.class ); + + if ( FilePolicy.OVERWRITE.equals( filePolicy ) ) + { + // No op + } + else + { // It is default to stop process + return ; + } + + } + + final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + final ZipOutputStream zipOut = new ZipOutputStream( byteOut ); + + try + { + final Queue<String> directories = new LinkedList<String>(); + + directories.add( baseDir ); + + while ( !directories.isEmpty() ) + { + final String filePath = directories.remove(); + final Object type = handler.get( filePath, Attribute.TYPE ); + + logger.trace( "File path :{}", filePath ); + + if ( + !FilenameUtil.equals( filePath, baseDir ) && + !filter.accept( baseDir, FilenameUtil.getRelativePath( baseDir, filePath ) ) + ) + { + logger.debug( "Ignore {}", filePath ); + continue; + } + logger.trace( "file [{}]'s type :{}", filePath, type ); + if ( Type.DIRECTORY.equals( type ) ) + { + final Collection<String> childs = handler.list( filePath ); + directories.addAll( childs ); + } + else if ( Type.FILE.equals( type ) ) + { + final String relative = getRelativePath( baseDir, filePath ); + final ZipEntry entry = new ZipEntry( relative ); + zipOut.putNextEntry( entry ); + IOUtil.redirect( handler.read( filePath ), zipOut ); + logger.debug( "Zip {}", relative ); + } + } + try { + handler.write( path, new ByteArrayInputStream( byteOut.toByteArray() ) ); + context.getPrompter().notify( MessageFormat.format( "Widget[{0}] is created successfully ", path ) ); + } + catch ( IOException e ) + { + throw new IllegalStateException( e ); + // TODO Handle + } + } + catch( IOException e ) + { + + // TODO Handle + } + finally + { + tryClose( zipOut ); + } + + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java b/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java new file mode 100644 index 000000000..c25d7cfb2 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java @@ -0,0 +1,66 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p> + * AbstractFileHandler. + * + * Abstract class for {@link FileHandler} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +abstract public class +AbstractFileHandler +implements FileHandler +{ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#is(java.lang.String, org.tizen.common.file.FileHandler.Attribute) + */ + @Override + public boolean is( + final String path, + final Attribute name + ) + throws IOException + { + final Object obj = get( path, name ); + if ( obj instanceof Boolean ) + { + return (Boolean) obj; + } + return false; + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java b/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java new file mode 100644 index 000000000..5e98ad426 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java @@ -0,0 +1,448 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +import static org.tizen.common.util.CollectionUtil.concatenate; +import static org.tizen.common.util.CollectionUtil.removeLast; +import static org.tizen.common.util.FilenameUtil.getCanonicalForm; +import static org.tizen.common.util.FilenameUtil.getRelativePath; +import static org.tizen.common.util.FilenameUtil.isAncestor; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Queue; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.tizen.common.util.FilenameUtil; +import org.tizen.common.util.ObjectUtil; + +/** + * <p> + * EclipseFileHandler. + * + * {@link FileHandler} for eclipse plugin + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +EclipseFileHandler +extends StandardFileHandler +{ + + /** + * @return + */ + protected + IWorkspaceRoot + getWorkspace() + { + return ResourcesPlugin.getWorkspace().getRoot(); + } + + protected IResource getFile( final String path ) throws IOException + { + final String root = getWorkspace().getLocation().toPortableString(); + logger.trace( "Path :{}, Root :{}", path, root ); + + final File fileChecker = new File( path ); + String relativePath = path; + if ( isAncestor( root, path ) ) + { + relativePath = getRelativePath( root, path ); + } + else if ( fileChecker.isAbsolute() ) + { + return null; + } + + final Queue<String> fragments = + new LinkedList<String>( Arrays.asList( FilenameUtil.getCanonicalFragments( relativePath ) ) ); + + final String projectName = fragments.remove(); + if ( ".metadata".equals( projectName ) ) + { + return null; + } + final IProject project = getWorkspace().getProject( projectName ); + if ( fragments.isEmpty() ) + { + return project; + } + + final String fileName = removeLast( fragments ); + + IContainer parent = project; + if ( !fragments.isEmpty() ) + { + parent = project.getFolder( concatenate( fragments, "/" ) ); + } + + try { + final IResource[] children = parent.members(); + for ( final IResource chlid : children ) + { + if ( ObjectUtil.equals( fileName, chlid.getName() ) ) + { + return chlid; + } + } + fragments.add( fileName ); + final String relativeFile = concatenate( fragments, "/" ); + return project.getFile( relativeFile ); + } catch ( + CoreException e + ) + { + logger.warn( "Exception :{}", e ); + } + return null; + } + + protected IContainer getFolder( final String path ) + { + final String root = getWorkspace().getLocation().toPortableString(); + logger.trace( "Path :{}, Root :{}", path, root ); + final File fileChecker = new File( path ); + String relativePath = path; + if ( isAncestor( root, path ) ) + { + relativePath = getRelativePath( root, path ); + } + else if ( fileChecker.isAbsolute() ) + { + return null; + } + + final Queue<String> fragments = + new LinkedList<String>( Arrays.asList( FilenameUtil.getCanonicalFragments( relativePath ) ) ); + + final String projectName = fragments.remove(); + if ( ".metadata".equals( projectName ) ) + { + return null; + } + final IProject project = getWorkspace().getProject( projectName ); + if ( fragments.isEmpty() ) + { + return project; + } + + final String fileName = removeLast( fragments ); + + IContainer parent = project; + if ( !fragments.isEmpty() ) + { + parent = project.getFolder( concatenate( fragments, "/" ) ); + } + + try { + final IResource[] children = parent.members(); + for ( final IResource chlid : children ) + { + if ( ObjectUtil.equals( fileName, chlid.getName() ) ) + { + return (IContainer) chlid; + } + } + fragments.add( fileName ); + final String relativeFile = concatenate( fragments, "/" ); + return project.getFolder( relativeFile ); + } catch ( + CoreException e + ) + { + } + return null; + + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory() + */ + @Override + public + String + getCurrentWorkingDirectory() + { + return getWorkspace().getLocation().toPortableString(); + } + + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String) + */ + @Override + public + void + setCurrentWorkingDirectory( + final String cwd + ) + { + throw new UnsupportedOperationException(); + + } + + @Override + public + void + makeDirectory( + final String path + ) + throws IOException + { + final File file = new File( path ); + if ( file.isAbsolute() ) + { + super.makeDirectory( path ); + final Path p = new Path( path ); + try { + getWorkspace().getFileForLocation( p ).refreshLocal( -1, new NullProgressMonitor() ); + } catch ( final CoreException e ) + { + throw new IOException( e ); + } + } + + } + + @Override + public + void + moveDirectory( + final String source, + final String target + ) + throws IOException + { + throw new UnsupportedOperationException(); + } + + @Override + public void copyDirectory(String source, String target) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void removeDirectory(String path) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public + Collection<String> + list( + final String path + ) + throws IOException + { + + final IContainer folder = getFolder( path ); + if ( null == folder ) + { + return super.list( path ); + } + try { + final IResource[] children = folder.members(); + final ArrayList<String> ret = new ArrayList<String>(); + + for ( final IResource child : children ) + { + + String childPath = getCanonicalForm( child.getLocation().toPortableString() ); + + if ( child instanceof IContainer ) + { + childPath = childPath + "/"; + } + + if ( childPath.startsWith( "/" ) ) + { + ret.add( childPath.substring( 1 ) ); + } + else + { + ret.add( childPath ); + } + } + + logger.trace( "Children :{}", ret ); + return ret; + } + catch ( + final CoreException e + ) + { + throw new IOException( e ); + } + } + + @Override + public void write(String path, InputStream out) throws IOException { + logger.trace( "Path :{}", path ); + final IResource file = getFile( path ); + final IFile f = (IFile) file.getAdapter( IFile.class ); + + try { + if ( f.exists() ) + { + f.setContents( out, false, false, new NullProgressMonitor() ); + } + else + { + f.create( out, false, new NullProgressMonitor() ); + } + } + catch ( final CoreException e ) + { + throw new IOException( e ); + } + } + + @Override + public InputStream read( + final String path + ) + throws IOException + { + final Path p = new Path( path ); + final IFile eFile = getWorkspace().getFileForLocation( p ); + if ( null == eFile ) + { + return super.read( path ); + } + try + { + return eFile.getContents(); + } + catch ( final CoreException e ) + { + throw new IOException( e ); + } + } + + @Override + public void moveFile(String source, String target) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void copyFile(String source, String target) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void removeFile(String path) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public Object get(String path, Attribute name) throws IOException { + logger.trace( "Path :{}, Attribute :{}", path, name ); + + final IResource file = getFile( path ); + if ( null == file ) + { + return super.get( path, name ); + } + + if ( Attribute.TYPE.equals( name ) ) + { + if ( file instanceof IContainer ) + { + return Type.DIRECTORY; + } + else if ( file instanceof IFile ) + { + return Type.FILE; + } + } + else if ( Attribute.EXISTS.equals( name ) ) + { + return file.exists(); + + } + else if ( Attribute.PATH.equals( name ) ) + { + return file.getLocation().toPortableString(); + } + else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) ) + { + return file.getLocationURI().toURL().toString(); + } + else if ( Attribute.MODIFIED.equals( name ) ) + { + return file.getLocalTimeStamp(); + } + else if ( Attribute.HIDDEN.equals( name ) ) + { + return file.isHidden(); + } + else if ( Attribute.READABLE.equals( name ) ) + { + return file.isAccessible(); + } + else if ( Attribute.WRITABLE.equals( name ) ) + { + return file.isAccessible(); + } + throw new IOException( path + "'s Unknown attribute :" + name ); + } + + @Override + public void set(String path, Attribute name, Object value) + throws IOException { + if ( Attribute.QUALIFIED.equals( name ) ) + { +// signatureFile.setPersistentProperty(SignatureUtility.stateQualifiedName, "false"); //$NON-NLS-1$ + return ; + } + + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() + { + return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/file/FileHandler.java b/org.tizen.common/src/org/tizen/common/file/FileHandler.java new file mode 100644 index 000000000..61d7a81b1 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/FileHandler.java @@ -0,0 +1,235 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; + +/** + * <p> + * FileHandler. + * + * Class to handle file system as abstract api + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +FileHandler +{ + /** + * <p> + * Attribute. + * + * File attribute + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ + enum Attribute + { + CWD, // Current Working Directory + PATH, // Abstract canonical path + TYPE, // Type( FILE / DIRECTORY / UNKNOWN ) + EXISTS, // true / false + READABLE, // true / false + WRITABLE, // true / false + HIDDEN, // true / false + READONLY, // true / false + MODIFIED, // long + URI, // String + URL, // String + QUALIFIED, + CUSTOM + } + + /** + * <p> + * Type. + * + * Value of {@link Attribute#TYPE} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ + enum Type + { + FILE, + DIRECTORY, + UNKNOWN + } + + /** + * Return cwd, abbreviating current working directory + * + * @return current working directory + */ + String getCurrentWorkingDirectory(); + + /** + * Change current working directory to <code>cwd</code> + * + * @param cwd new current working directory + */ + void setCurrentWorkingDirectory( final String cwd ); + + /* Directory */ + /** + * Make new directory with <code>path</code> + * + * @param path path to directory + * + * @throws IOException If exception occured in making a directory + */ + void makeDirectory( String path ) throws IOException; + + /** + * Move <code>source</code> directory to <code>target</code> + * + * @param source directory path to move + * @param target path to move to + * + * @throws IOException If exception occured in moving a directory + */ + void moveDirectory( String source, String target ) throws IOException; + + /** + * Copy <code>source</code> directory to <code>target</code> + * + * @param source directory path to copy + * @param target path to copy to + * + * @throws IOException If exception occured in copying a directory + */ + void copyDirectory( String source, String target ) throws IOException; + + /** + * Delete <code>path</code> directory + * + * @param path directory path to delete + * + * @throws IOException If exception occured in deleting a directory + */ + void removeDirectory( String path ) throws IOException; + + /** + * List child directory and file in <code>path</code> + * + * @param path directory path + * @return child directory and file's path + * + * @throws IOException If exception occured in list child in directory + */ + Collection<String> list( String path ) throws IOException; + + /* File */ + /** + * Save file in <code>path</code> using <code>out</code> + * + * @param path file path to write + * @param out {@link InputStream} to provide contents + * + * @throws IOException If exception occured in saving + */ + void write( String path, InputStream out ) throws IOException; + + /** + * Return {@link InputStream} to provice file contents + * + * @param path file path to read + * @return + * @throws IOException + */ + InputStream read( String path ) throws IOException; + + /** + * Move <code>source</code> file to <code>target</code> + * + * @param source file path to move + * @param target path to move to + * + * @throws IOException If exception occured in moving a file + */ + void moveFile( String source, String target ) throws IOException; + + /** + * Copy <code>source</code> file to <code>target</code> + * + * @param source file path to copy + * @param target path to copy to + * + * @throws IOException If exception occured in copying a file + */ + void copyFile( String source, String target ) throws IOException; + + /** + * Delete file in <code>path</code> + * + * @param path file path + * + * @throws IOException If exception occured in deletion + */ + void removeFile( String path ) throws IOException; + + /** + * Return <code>path</code>'s attribute value having <code>name</code> as attribute name + * + * @param path file path + * @param name attribute name + * + * @return attribute value + * + * @throws IOException If exception occured in reading attribute + */ + Object get( final String path, Attribute name ) throws IOException; + + /** + * Check if <code>path</code> file's attribute <code>name</code> is <code>true</code> + * + * @param path file path to check + * @param name attribute name + * + * @return boolean value if thread is <code>name</code> attribute + * + * @throws IOException If exception occured in reading attribute + */ + boolean is( final String path, Attribute name ) throws IOException; + + /** + * Set <code>path</code> file's attribute <code>name</code> as <code>value</code> + * + * @param path file path + * @param name attribute anme + * @param value attribute value + * + * @throws IOException If exception occured in change file attribute + * + * @see {@link Attribute} + */ + void set( final String path, Attribute name, Object value ) throws IOException; + +} diff --git a/org.tizen.common/src/org/tizen/common/file/Filter.java b/org.tizen.common/src/org/tizen/common/file/Filter.java new file mode 100644 index 000000000..17af932db --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/Filter.java @@ -0,0 +1,48 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +/** + * <p> + * Filter. + * + * Object to check if path is valid + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface Filter +{ + /** + * Check and return if <code>path</code> is valid when current working directory is <code>cwd</code> + * + * @param cwd current working directory + * @param path file path + * + * @return boolean value of validation + */ + boolean accept( final String cwd, final String path ); +} diff --git a/org.tizen.common/src/org/tizen/common/file/PatternFilter.java b/org.tizen.common/src/org/tizen/common/file/PatternFilter.java new file mode 100644 index 000000000..f0600870e --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/PatternFilter.java @@ -0,0 +1,77 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +/** + * <p> + * PatternFilter. + * + * {@link Filter} using pattern + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +PatternFilter +{ + /** + * Pattern string + */ + protected String pattern = "*"; + + /** + * Return pattern + * + * @return pattern + * + * {@link #pattern} + */ + public + String + getPattern() + { + return this.pattern; + } + + /** + * Set pattern + * + * @param pattern pattern to set + */ + public + void + setPattern( + final String pattern + ) + { + if ( null == pattern ) + { + throw new NullPointerException(); + } + this.pattern = pattern; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java b/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java new file mode 100644 index 000000000..efd37f599 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java @@ -0,0 +1,193 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.util.CollectionUtil; + +/** + * <p> + * SimpleFileFilter. + * + * File filter using including filter and excluding filter + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +SimpleFileFilter +implements Filter +{ + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Including filters + */ + protected List<Filter> includes = new ArrayList<Filter>(); + + /** + * Excluding filters + */ + protected List<Filter> excludes = new ArrayList<Filter>(); + + // Hiding collection + /** + * Clear including filters + */ + public + void + clearIncludes() + { + includes.clear(); + } + + /** + * Set <code>filters</code> including filters + * + * @param filters {@link Filter}s to set + */ + public + void + setIncludes( + final Filter... filters + ) + { + clearIncludes(); + addIncludes( filters ); + } + + /** + * Add <code>filters</code> to including filters + * + * @param filters {@link Filter}s to add + */ + public + void + addIncludes( + final Filter... filters + ) + { + for( final Filter filter : filters ) + { + includes.add( filter ); + } + logger.debug( "Include filters[{}] added", CollectionUtil.toString( filters ) ); + } + + /** + * Clear excluding filters + */ + public + void + clearExcludes() + { + excludes.clear(); + } + + /** + * Set {@link Filter}s as excluding filters + * @param filters + */ + public + void + setExcludes( + final Filter... filters + ) + { + clearExcludes(); + addExcludes( filters ); + } + + /** + * Add <code>filters</code> to excluding filters + * + * @param filters {@link Filter}s to add + */ + public + void + addExcludes( + final Filter... filters + ) + { + for( final Filter filter : filters ) + { + excludes.add( filter ); + } + logger.debug( "Excludes filters[{}] added", CollectionUtil.toString( filters ) ); + } + + + /* (non-Javadoc) + * @see org.tizen.common.file.Filter#accept(java.lang.String, java.lang.String) + */ + @Override + public + boolean + accept( + final String cwd, + final String path + ) + { + logger.trace( "Current working directory :{}, Path :{}", cwd, path ); + logger.trace( "Excluding filters :{}", excludes ); + for ( final Filter filter : excludes ) + { + if ( filter.accept( cwd, path ) ) + { + logger.debug( "Deny because of {}", filter ); + return false; + } + } + + logger.trace( "Including filters :{}", excludes ); + for ( final Filter filter : includes ) + { + if ( filter.accept( cwd, path ) ) + { + logger.debug( "Accept because of {}", filter ); + return true; + } + } + + if ( includes.isEmpty() ) + { + return true; + } + else if ( excludes.isEmpty() ) + { + return false; + } + throw new IllegalStateException( "Include and Exclude rule is invalid" ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java b/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java new file mode 100755 index 000000000..a0b852e84 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java @@ -0,0 +1,394 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ + +package org.tizen.common.file; + +import static org.tizen.common.util.FilenameUtil.getCanonicalForm; +import static org.tizen.common.util.IOUtil.tryClose; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; + +import org.tizen.common.util.IOUtil; + +/** + * <p> + * StandardFileHandler. + * + * {@link FileHandler} to use java.io package api like {@link File}, {@link FileInputStream} and {@link FileOutputStream} + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +StandardFileHandler +extends AbstractFileHandler +{ + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory() + */ + @Override + public + String + getCurrentWorkingDirectory() + { + return new File( "." ).getAbsolutePath(); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String) + */ + @Override + public + void + setCurrentWorkingDirectory(String cwd) { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#makeDirectory(java.lang.String) + */ + @Override + public + void + makeDirectory( + final String path + ) + throws IOException + { + new File( path ).mkdir(); + + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#moveDirectory(java.lang.String, java.lang.String) + */ + @Override + public + void + moveDirectory( + final String source, + final String target + ) + throws IOException + { + final File file = new File( source ); + if ( !file.isDirectory() ) + { + throw new IOException(); + } + file.renameTo( new File( target ) ); + + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#copyDirectory(java.lang.String, java.lang.String) + */ + @Override + public + void + copyDirectory( + final String source, + final String target + ) + throws IOException + { + throw new UnsupportedOperationException(); +// final Stack<File> sourceStack = new Stack<File>(); +// final Stack<File> targetStack = new Stack<File>(); +// sourceStack.push( new File(source ) ); +// targetStack.push( new File( target ) ); +// +// while ( !sourceStack.isEmpty() ) +// { +// final File sourceFile = sourceStack.pop(); +// final File targetFile = targetStack.pop(); +// +// if ( sourceFile.isDirectory() ) +// { +// targetFile.mkdir(); +// for ( final File sourceChild : sourceFile.listFiles() ) +// { +// sourceStack.push( sourceChild ); +// targetStack.push( new File( targetFile, sourceChild.getName() ) ); +// } +// } +// else if ( sourceFile.isFile()) +// { +// final FileInputStream fileIn = new FileInputStream( sourceFile ); +// final FileOutputStream fileOut = new FileOutputStream( targetFile ); +// +// IOUtil.redirect( fileIn, fileOut ); +// tryClose( fileOut, fileIn ); +// } +// else { +// Logger.error(sourceFile + " is not file or directory"); +// } +// } + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#removeDirectory(java.lang.String) + */ + @Override + public + void + removeDirectory( + final String path + ) + throws IOException + { + if ( !Type.DIRECTORY.equals( get( path, Attribute.TYPE ) ) ) + { + throw new IOException(); + } + + for ( final String childPath : list( path ) ) + { + Object type = get( childPath, Attribute.TYPE ); + if ( Type.DIRECTORY.equals( type ) ) + { + removeDirectory( childPath ); + } + else if ( Type.FILE.equals( type ) ) + { + removeFile( childPath ); + } + } + + new File( path ).delete(); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#list(java.lang.String) + */ + @Override + public + Collection<String> + list( + final String path + ) + throws IOException + { + final File file = new File( path ); + final File[] children = file.listFiles(); + final ArrayList<String> ret = new ArrayList<String>(); + for ( final File child : children ) + { + ret.add( getCanonicalForm( child.getAbsolutePath() ) ); + } + + return ret; + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#write(java.lang.String, java.io.InputStream) + */ + @Override + public + void + write( + final String path, + final InputStream in + ) + throws IOException + { + final FileOutputStream fileOut = new FileOutputStream( path ); + + try + { + IOUtil.redirect( in, fileOut ); + } + finally + { + tryClose( fileOut ); + } + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#read(java.lang.String) + */ + @Override + public + InputStream + read( + final String path + ) + throws IOException + { + return new FileInputStream( path ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#moveFile(java.lang.String, java.lang.String) + */ + @Override + public + void + moveFile( + final String source, + final String target + ) + throws IOException + { + final File file = new File( source ); + if ( !file.isFile() ) + { + throw new IOException(); + } + file.renameTo( new File( target ) ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#copyFile(java.lang.String, java.lang.String) + */ + @Override + public + void + copyFile( + final String source, + final String target + ) + throws IOException + { + final File file = new File( source ); + if ( !file.isFile() ) + { + throw new IOException(); + } + + final FileInputStream sourceIn = new FileInputStream( source ); + final FileOutputStream targetOut = new FileOutputStream( target ); + try + { + IOUtil.redirect( sourceIn, targetOut ); + } + finally + { + tryClose( targetOut, sourceIn ); + } + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#removeFile(java.lang.String) + */ + @Override + public + void + removeFile( + final String path + ) + throws IOException + { + final File file = new File( path ); + if ( !file.isFile() ) + { + throw new IOException(); + } + + file.delete(); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#get(java.lang.String, org.tizen.common.file.FileHandler.Attribute) + */ + @Override + public + Object + get( + final String path, + final Attribute name + ) + throws IOException + { + logger.trace( "Path :{}, Attribute :{}", path, name ); + + final File file = new File( path ); + + if ( Attribute.TYPE.equals( name ) ) + { + if ( file.isDirectory() ) + { + return Type.DIRECTORY; + } + else if ( file.isFile() ) + { + return Type.FILE; + } + } + else if ( Attribute.EXISTS.equals( name ) ) + { + return file.exists(); + + } + else if ( Attribute.PATH.equals( name ) ) + { + return file.getCanonicalPath(); + } + else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) ) + { + return file.toURI().toURL().toString(); + } + else if ( Attribute.MODIFIED.equals( name ) ) + { + return file.lastModified(); + } + else if ( Attribute.HIDDEN.equals( name ) ) + { + return file.isHidden(); + } + else if ( Attribute.READABLE.equals( name ) ) + { + return file.canRead(); + } + else if ( Attribute.WRITABLE.equals( name ) ) + { + return file.canWrite(); + } + throw new IOException( path + "'s Unknown attribute :" + name ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#set(java.lang.String, org.tizen.common.file.FileHandler.Attribute, java.lang.Object) + */ + @Override + public void + set( + final String path, + final Attribute name, + final Object value + ) + throws IOException + { + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java b/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java new file mode 100644 index 000000000..c35f4d084 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java @@ -0,0 +1,798 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file; + +import static org.tizen.common.util.ArrayUtil.size; +import static org.tizen.common.util.FilenameUtil.SEPARATOR_DIRECTORY; +import static org.tizen.common.util.FilenameUtil.addTailingPath; +import static org.tizen.common.util.FilenameUtil.getCanonicalFragments; +import static org.tizen.common.util.FilenameUtil.getFilename; +import static org.tizen.common.util.FilenameUtil.removeTailingPath; +import static org.tizen.common.util.IOUtil.tryClose; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.util.IOUtil; +import org.tizen.common.util.StringUtil; + +/** + * <p> + * VirtualFileHandler. + * + * {@link FileHandler} to handling in memory + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +VirtualFileHandler +extends AbstractFileHandler +{ + + /** + * <p> + * File. + * + * File contents container + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ + private class + File + implements Cloneable + { + /** + * File name + */ + String name; + + /** + * File contents + */ + byte[] contents; + + /** + * File attributes + */ + HashMap<Attribute, Object> attr = new HashMap<Attribute, Object>(); + + /** + * Default constructor + */ + public File() + { + } + + /** + * Constructor with name and contents + * + * @param name file name + * @param contents file contents + */ + public + File( + final String name, + final byte[] contents + ) + { + this.name = name; + this.contents = contents; + } + + /** + * Return file name + * + * @return file name + */ + public + String + getName() + { + return this.name; + } + + /** + * Return file contents + * + * @return file contents + */ + public + byte[] getContents() + { + return this.contents; + } + + /** + * Set <code>contents</code> as file contents + * + * @param contents new file contents + */ + public + void + setContents( + final byte[] contents + ) + { + this.contents = contents; + } + + /** + * Set file attribute value whose name is <code>name</code> as <code>value</code> + * + * @param name attribute name + * @param value attribute value + */ + public + void + setAttribute( + final Attribute name, + final Object value + ) + { + attr.put( name, value ); + } + /** + * Return file attribute value whose name is <code>name</code> + * + * @param name attribute name + * + * @return attribute value + */ + public + Object + getAttribute( + final Attribute name + ) + { + return attr.get( name ); + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + @Override + public + Object + clone() + { + final File file = new File(); + file.name = this.name; + file.contents = this.contents; + return file; + } + + } + + /** + * <p> + * Directory. + * + * Directory in memory + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ + class Directory + extends File + implements Cloneable + { + /** + * Child files & directories + */ + protected final HashMap<String, File> name2file = new HashMap<String, File>(); + + /** + * Default constructor + */ + public Directory() + { + } + + /** + * Constructor with directory name + * + * @param name directory name + */ + public + Directory( + final String name + ) + { + super( name, null ); + } + + /** + * Return child file whose name is <code>name</code> + * + * @param name file name + * + * @return {@link File} + */ + public + File + get( + final String name + ) + { + return name2file.get( name ); + } + + /** + * Delete child file whose name is <code>name</code> + * + * @param name file name + * + * @return file to be deleted + */ + public + File + remove( + final String name + ) + { + return name2file.remove( name ); + } + + /** + * Add new file whose name is <code>contents<code> and whose contents is <code>contents</code> + * + * @param name file name + * @param contents file contents + */ + public + void + add( + final String name, + final byte[] contents + ) + { + name2file.put( name, new File( name, contents ) ); + } + + /** + * Add directory whose name is <code>name</code> + * + * @param name directory name + */ + public + void + add( + final String name + ) + { + name2file.put( name, new Directory( name ) ); + } + + /** + * Add <code>file</code> + * + * @param file file or directory to add + */ + public + void + add( + final File file + ) + { + name2file.put( file.getName(), file ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.VirtualFileHandler.File#clone() + */ + @Override + public + Object + clone() + { + final Directory dir = new Directory(); + dir.contents = this.contents; + dir.name = this.name; + for ( final String name : name2file.keySet() ) + { + name2file.put( name, (File) name2file.get( name ).clone() ); + } + + return dir; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + return name2file.keySet().toString(); + } + } + + /** + * Prefix abstract path + */ + protected static final String ROOT_PREFIX = "/"; + + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Root directory + */ + protected final Directory root = new Directory(); + + /** + * Current working directory + */ + protected String cwd = "/"; + + /** + * Return {@link File} matching with <code>path</code> + * + * @param path file path + * @return {@link File} matching with <code>path</code> + * + * @throws IOException If file is not accessible + */ + protected + File + getFile( + final String path + ) + throws IOException + { + logger.trace( "Path :{}", path ); + + final String[] fragments = getCanonicalFragments( path ); + + File iter = root; + for ( int i = 0, n = fragments.length ; i < n ; ++i ) + { + Directory dir = (Directory) iter; + iter = dir.get( fragments[i] ); + if ( null == iter ) + { + logger.debug( "fragment :{}", fragments[i] ); + logger.debug( "in-processing directory :{}", dir ); + + throw new IOException( "Can't access " + path ); + } + } + + return iter; + } + + /** + * Return parent directory of file matching with <code>path</code> + * @param path file path + * + * @return parent directory + * + * @throws IOException If file or directory is not accessible + */ + public + Directory + getParent( + final String path + ) + throws IOException + { + final File parent = getFile( removeTailingPath( path, 1 ) ); + if ( !( parent instanceof Directory ) ) + { + throw new IOException(); + } + + return (Directory) parent; + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#makeDirectory(java.lang.String) + */ + @Override + public + void + makeDirectory( + final String path + ) + throws IOException + { + final Directory parent = getParent( path ); + final String dirName = getFilename( path ); + parent.add( dirName ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#moveDirectory(java.lang.String, java.lang.String) + */ + @Override + public + void + moveDirectory( + final String source, + final String target + ) + throws IOException + { + final String filename = getFilename( source ); + + final Directory parent = getParent( source ); + final File file = parent.get( filename ); + if ( !( file instanceof Directory ) ) + { + throw new IOException(); + } + final Directory newParent = (Directory) getFile( target ); + newParent.add( newParent.remove( filename ) ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#copyDirectory(java.lang.String, java.lang.String) + */ + @Override + public + void + copyDirectory( + final String source, + final String target + ) + throws IOException + { + final Directory dir = (Directory) getFile( source ); + final Directory targetDir = (Directory) getFile( target ); + + targetDir.add( (File) dir.clone() ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#removeDirectory(java.lang.String) + */ + @Override + public + void + removeDirectory( + final String path + ) + throws IOException + { + final Directory dir = getParent( path ); + final String name = getFilename( path ); + dir.remove( name ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#list(java.lang.String) + */ + @Override + public + Collection<String> + list( + final String path + ) + throws IOException + { + final Directory dir = (Directory) getFile( path ); + final Collection<String> childNames = dir.name2file.keySet(); + logger.trace( "Directory[{}]'s child :{}", path, childNames ); + + final ArrayList<String> fullNames = new ArrayList<String>(); + + for ( final String name : dir.name2file.keySet() ) + { + fullNames.add( addTailingPath( path, name ) ); + } + + logger.debug( "Fullnames :\n{}", fullNames ); + return fullNames; + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#write(java.lang.String, java.io.InputStream) + */ + @Override + public + void + write( + final String path, + final InputStream in + ) + throws IOException + { + final Directory parent = getParent( path ); + if ( !(parent instanceof Directory ) ) + { + throw new IOException(); + } + + final String filename = getFilename( path ); + + File file = parent.get( filename ); + + if ( file instanceof Directory ) + { + throw new IOException(); + } + if ( null == file ) + { + file = new File( getFilename( path ), null ); + } + getParent( path ).add( file ); + + final byte[] contents = IOUtil.getBytes( in ); + + if ( logger.isTraceEnabled() ) + { + int nSize = size( contents ); + logger.trace( + "Save file[{}] :{} byte(s)\n{}", + new Object[] { + path, + nSize, + StringUtil.text2hexa( contents, 0, Math.min( 64, size( contents ) ) ) + ( (64 < size( contents ) )?"...":"" ) + } + ); + } + + file.setContents( contents ); + } + + /** + * write <code>contents</code> to file with <code>path</code> + * + * @param path file path + * @param contents file contents + * + * @throws IOException If file can't be writable + * + * @see {@link #write(String, InputStream)} + */ + public + void + write( + final String path, + final String contents + ) + throws IOException + { + logger.trace( "Save file :{}\n{}", path, contents ); + final InputStream in = new ByteArrayInputStream( (null==contents)?(new byte[0]):contents.getBytes() ); + try + { + write( path, in ); + } + finally + { + tryClose( in ); + } + + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#read(java.lang.String) + */ + @Override + public + InputStream + read( + final String path + ) + throws IOException + { + final File file = getFile( path ); + if ( file instanceof Directory ) + { + throw new IOException(); + } + + return new ByteArrayInputStream( file.contents ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#moveFile(java.lang.String, java.lang.String) + */ + @Override + public + void + moveFile( + final String source, + final String target + ) + throws IOException + { + final Directory directory = getParent( source ); + final String fileName = getFilename( source ); + final File file = directory.remove( fileName ); + if ( null == file ) + { + throw new IOException(); + } + + final Directory targetDirectory = (Directory) getFile( target ); + targetDirectory.add( file ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#copyFile(java.lang.String, java.lang.String) + */ + @Override + public + void + copyFile( + final String source, + final String target + ) + throws IOException + { + final Directory directory = getParent( source ); + final String fileName = getFilename( source ); + final File file = directory.get( fileName ); + if ( null == file ) + { + throw new IOException(); + } + + final Directory targetDirectory = (Directory) getFile( target ); + targetDirectory.add( (File) file.clone() ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#removeFile(java.lang.String) + */ + @Override + public + void + removeFile( + final String path + ) + throws IOException + { + final File file = getFile( path ); + if ( file instanceof Directory ) + { + throw new IOException(); + } + + final Directory directory = getParent( path ); + final String fileName = getFilename( path ); + directory.remove( fileName ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#get(java.lang.String, org.tizen.common.file.FileHandler.Attribute) + */ + @Override + public + Object + get( + final String path, + final Attribute name + ) + throws IOException + { + File file = null; + try { + file = getFile( path ); + } catch ( Throwable e ) + { + } + if ( Attribute.TYPE.equals( name ) ) + { + if ( file instanceof Directory ) + { + return Type.DIRECTORY; + } + else if ( file instanceof File ) + { + return Type.FILE; + } + } + else if ( Attribute.EXISTS.equals( name ) ) + { + return ( null != file ); + + } + else if ( Attribute.PATH.equals( name ) ) + { + if ( path.startsWith( ROOT_PREFIX ) ) + { + return path; + } + + return cwd + SEPARATOR_DIRECTORY + path; + } + else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) ) + { + return "vf://" + path; + } + else + { + file.getAttribute( name ); + return false; + } + throw new IOException( path + "'s Unknown attribute :" + name ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#set(java.lang.String, org.tizen.common.file.FileHandler.Attribute, java.lang.Object) + */ + @Override + public + void + set( + final String path, + final Attribute name, + final Object value + ) + throws IOException + { + File file = null; + try { + file = getFile( path ); + } catch ( Throwable e ) + { + } + if ( null != file ) + { + file.setAttribute( name, value ); + } + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory() + */ + @Override + public + String + getCurrentWorkingDirectory() { + return this.cwd; + } + + /* (non-Javadoc) + * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String) + */ + @Override + public + void + setCurrentWorkingDirectory( + final String cwd + ) + { + this.cwd = cwd; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java new file mode 100644 index 000000000..04ccb0e57 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java @@ -0,0 +1,96 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file.filter; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.file.Filter; +import org.tizen.common.file.PatternFilter; +import org.tizen.common.util.FilenameUtil; + +/** + * WildCardFilter + * + * Filter using wildcard( ?, * ) + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +WildCardFilter +extends PatternFilter +implements Filter +{ + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Default constructor + */ + public WildCardFilter() + { + } + + /** + * Constructor with pattern + * + * @param pattern pattern to apply + */ + public WildCardFilter( final String pattern ) + { + setPattern( pattern ); + } + + /* (non-Javadoc) + * @see org.tizen.common.file.Filter#accept(java.lang.String, java.lang.String) + */ + @Override + public + boolean + accept( + final String cwd, + final String path + ) + { + logger.trace( "Current working directory :{}, Path :{}", cwd, path ); + final String name = FilenameUtil.getFilename( path ); + logger.trace( "Name :{}", name ); + return FilenameUtils.wildcardMatch( name, getPattern() ); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + return WildcardFileFilter.class.getName() + "[" + getPattern() + "]"; + } +} diff --git a/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java new file mode 100644 index 000000000..2cafcbfb9 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java @@ -0,0 +1,60 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.file.filter; + +import org.tizen.common.FactoryWithArgument; +import org.tizen.common.file.Filter; + +/** + * <p> + * WildCardFilterFactory. + * + * Factory to create {@link WildCardFilter} for pattern + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +WildCardFilterFactory +implements FactoryWithArgument<Filter, String> +{ + + /* (non-Javadoc) + * @see org.tizen.common.FactoryWithArgument#create(java.lang.Object) + */ + @Override + public + Filter + create( + final String arg + ) + { + final WildCardFilter filter = new WildCardFilter(); + filter.setPattern( arg ); + return filter; + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java b/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java deleted file mode 100644 index ba8c72731..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.handler; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.tizen.common.manager.StatusLineMessageManager; -import org.tizen.common.model.ITableModel; - - - -public class ClearHandler extends AbstractHandler { - private IViewPart part; - private TableViewer viewer; - private StatusLineMessageManager statusLine; - - private String message = Messages.ClearHandler_0; - - public Object execute(ExecutionEvent event) throws ExecutionException { - - part = (IViewPart)HandlerUtil.getActivePart(event); - viewer = (TableViewer)part.getSite().getSelectionProvider(); - statusLine = new StatusLineMessageManager(part); - - clearData(); - return null; - } - - private void clearData() throws ExecutionException { - ITableModel model = (ITableModel)viewer.getInput(); - model.clear(); - viewer.refresh(); - statusLine.setMessage(message); - } - - -} - diff --git a/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java b/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java deleted file mode 100644 index e31e5eed2..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Superclass for clipboard related handlers providing safe creation and
- * disposal of the {@link Clipboard}.
- */
-public abstract class ClipboardHandler extends AbstractHandler {
- public Object execute(ExecutionEvent event) throws ExecutionException {
- Clipboard clipboard = new Clipboard(HandlerUtil.getActiveShell(event)
- .getDisplay());
- try {
- return execute(event, clipboard);
- } finally {
- clipboard.dispose();
- }
- }
-
- protected abstract Object execute(ExecutionEvent event, Clipboard clipboard)
- throws ExecutionException;
-}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java b/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java deleted file mode 100644 index 54d604f79..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java +++ /dev/null @@ -1,101 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.eclipse.ui.part.ResourceTransfer;
-
-/**
- * Copy each currently selected object in the Favorites view to the clipboard.
- */
-public class CopyHandler extends ClipboardHandler {
- /**
- * Called by the superclass {@link #execute(ExecutionEvent)} method so that
- * this method can concentrate on the operation and does not have to manage
- * clipboard creation and disposal.
- */
- public Object execute(ExecutionEvent event, Clipboard clipboard)
- throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection instanceof IStructuredSelection) {
- Object[] objects = ((IStructuredSelection) selection).toArray();
- if (objects.length > 0) {
- try {
- clipboard.setContents(new Object[] { asResources(objects),
- asText(objects), }, new Transfer[] {
- ResourceTransfer.getInstance(),
- TextTransfer.getInstance(), });
- } catch (SWTError error) {
- // Copy to clipboard failed.
- // This happens when another application
- // is accessing the clipboard while we copy.
- // Ignore the error.
- }
- }
- }
- return null;
- }
-
- public static IResource[] asResources(Object[] objects) {
- Collection<IResource> resources = new ArrayList<IResource>(
- objects.length);
- for (int i = 0; i < objects.length; i++) {
- Object each = objects[i];
- if (each instanceof IAdaptable) {
- IResource res = (IResource) ((IAdaptable) each)
- .getAdapter(IResource.class);
- if (res != null)
- resources.add(res);
- }
- }
- return resources.toArray(new IResource[resources.size()]);
- }
-
- public static String asText(Object[] objects) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < objects.length; i++) {
- Object each = objects[i];
- if (each != null) {
- buf.append(each.toString());
- }
- buf.append(System.getProperty("line.separator")); //$NON-NLS-1$
- }
- return buf.toString();
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/handler/Messages.java b/org.tizen.common/src/org/tizen/common/handler/Messages.java deleted file mode 100644 index 7cb9e48ae..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/Messages.java +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.handler; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.tizen.common.handler.messages"; //$NON-NLS-1$ - public static String ClearHandler_0; - public static String OpenFileHandler_0; - public static String OpenFileHandler_2; - public static String OpenFileHandler_3; - public static String SaveFileHandler_0; - public static String SaveFileHandler_1; - public static String SaveFileHandler_11; - public static String SaveFileHandler_12; - public static String SaveFileHandler_4; - public static String SaveFileHandler_5; - static { - // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - } -} diff --git a/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java b/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java deleted file mode 100644 index f97b3e066..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java +++ /dev/null @@ -1,103 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.handler; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.filesystem.IFileInfo; -import org.eclipse.core.filesystem.IFileStore; -import org.eclipse.core.runtime.Path; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.ide.IDE; -import org.tizen.common.manager.StatusLineMessageManager; - - - -public class OpenFileHandler extends AbstractHandler { - private IViewPart part; - private String fileName; - private Shell shell; - private IWorkbenchPage page; - private StatusLineMessageManager statusLine; - - private final String title = Messages.OpenFileHandler_0; - private final String PARAMETER_ID = "org.tizen.common.command.openFile.parameter"; //$NON-NLS-1$ - - public Object execute(ExecutionEvent event) throws ExecutionException { - - part = (IViewPart)HandlerUtil.getActivePart(event); - shell = part.getSite().getShell(); - page = part.getSite().getPage(); - statusLine = new StatusLineMessageManager(part); - - String extension = event.getParameter(PARAMETER_ID); - - openFile(extension); - return null; - } - - private void openFile(String extension) throws ExecutionException { - fileName = getLoadFileName(extension); - if(fileName==null) - return; - - IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(fileName)); - IFileInfo fileInfo = fileStore.fetchInfo(); - fileInfo.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true); - - if( fileInfo.isDirectory()||!fileInfo.exists() ){ - statusLine.setErrorMessage(Messages.OpenFileHandler_2); - return; - } - - try { - IDE.openEditorOnFileStore(page, fileStore); - } catch (PartInitException e) { - statusLine.setErrorMessage(fileName+ Messages.OpenFileHandler_3); - return; - } - - } - - private String getLoadFileName(String extension) { - String[] extFilter = {"*."+extension}; //$NON-NLS-1$ - - FileDialog dialog = new FileDialog(shell, SWT.OPEN); - dialog.setFilterExtensions(extFilter); - dialog.setText(title); - return dialog.open(); - } - -} - diff --git a/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java b/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java deleted file mode 100644 index 32932b811..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.handler; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.preference.PreferenceDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.dialogs.PreferencesUtil; -import org.eclipse.ui.handlers.HandlerUtil; - -public class OpenPreferencesHandler extends AbstractHandler { - private IViewPart part; - private Shell shell; - private final String PARAMETER_ID = "org.tizen.common.command.setting.parameter"; //$NON-NLS-1$ - - public Object execute(ExecutionEvent event) throws ExecutionException { - - part = (IViewPart)HandlerUtil.getActivePart(event); - shell = part.getSite().getShell(); - - String preferenceId = event.getParameter(PARAMETER_ID); - openPreferences(preferenceId); - return null; - } - - private void openPreferences(String preferenceId) throws ExecutionException { - PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(shell, - preferenceId, null, null); - dialog.open(); - } - - - -} - diff --git a/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java b/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java deleted file mode 100644 index c703e302d..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java +++ /dev/null @@ -1,139 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.handler; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.tizen.common.manager.StatusLineMessageManager; -import org.tizen.common.model.ITableModel; -import org.tizen.common.util.DialogUtil; - - - -public class SaveFileHandler extends AbstractHandler { - private IViewPart part; - private TableViewer viewer; - private String fileName; - private Shell shell; - private StatusLineMessageManager statusLine; - - private final String title = Messages.SaveFileHandler_0; - private final String PARAMETER_ID = "org.tizen.common.command.saveFile.parameter"; //$NON-NLS-1$ - - - public Object execute(ExecutionEvent event) throws ExecutionException { - - part = (IViewPart)HandlerUtil.getActivePart(event); - shell = part.getSite().getShell(); - statusLine = new StatusLineMessageManager(part); - - viewer = (TableViewer)part.getSite().getSelectionProvider(); - String extension = event.getParameter(PARAMETER_ID); - - if(!hasRecord()) - return null; - - try { - saveFile(extension); - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - private void saveFile(String extension) throws InvocationTargetException, InterruptedException { - fileName = getSaveFileName(extension); - - if(fileName==null) - return; - - if(!fileName.endsWith("."+extension)) //$NON-NLS-1$ - fileName= fileName+"."+extension; //$NON-NLS-1$ - - if(!(new File(fileName).getParentFile().canWrite())){ - DialogUtil.openErrorDialog(Messages.SaveFileHandler_4); - return; - } - - part.getSite().getWorkbenchWindow().run(false, false, new IRunnableWithProgress(){ - public void run(IProgressMonitor monitor) { - monitor.beginTask(Messages.SaveFileHandler_5, 100); - writeRecord(); - monitor.done(); - } - }); - - showRecordCount(); - - } - - private String getSaveFileName(String extension) { - String[] extFilter = {"*."+extension,"*.*"}; //$NON-NLS-1$ //$NON-NLS-2$ - - FileDialog dialog = new FileDialog(shell, SWT.SAVE); - dialog.setFilterExtensions(extFilter); - dialog.setText(title); - dialog.setOverwrite(true); - dialog.setFileName("untitled."+extension); //$NON-NLS-1$ - dialog.setFilterPath(System.getProperty("user.home")); //$NON-NLS-1$ - - return dialog.open(); - } - - private void writeRecord() { - ITableModel model = (ITableModel) viewer.getInput(); - model.save(fileName); - } - - private void showRecordCount() { - int size = ((ITableModel) viewer.getInput()).size(); - statusLine.setMessage(Messages.SaveFileHandler_1+size+Messages.SaveFileHandler_11 + fileName); - } - - private boolean hasRecord() { - int size = ((ITableModel) viewer.getInput()).size(); - if(size==0){ - statusLine.setErrorMessage(Messages.SaveFileHandler_12); - return false; - }else - statusLine.setErrorMessage(""); //$NON-NLS-1$ - return true; - } -} - diff --git a/org.tizen.common/src/org/tizen/common/handler/messages.properties b/org.tizen.common/src/org/tizen/common/handler/messages.properties deleted file mode 100644 index f9d98c9af..000000000 --- a/org.tizen.common/src/org/tizen/common/handler/messages.properties +++ /dev/null @@ -1,10 +0,0 @@ -ClearHandler_0=All data is cleared -OpenFileHandler_0=Load File -OpenFileHandler_2=Input file doesn't exist or isn't a file -OpenFileHandler_3=isn't opened for internal error -SaveFileHandler_0=Save File -SaveFileHandler_1=Total -SaveFileHandler_11=\ record is saved into -SaveFileHandler_12=There is no record. -SaveFileHandler_4=You can store a file into the directory that has write permission. please select another directory -SaveFileHandler_5=Save File diff --git a/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java b/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java deleted file mode 100644 index 77d279e10..000000000 --- a/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ -package org.tizen.common.manager; - -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchPart; - -public class StatusLineMessageManager{ - private IViewPart part; - private IStatusLineManager manager; - - public StatusLineMessageManager(IWorkbenchPart part){ - this.part = (IViewPart)part; - this.manager = this.part.getViewSite().getActionBars().getStatusLineManager(); - } - - public void setErrorMessage(String message){ - manager.setErrorMessage(message); - } - - public void setMessage(String message){ - manager.setMessage(message); - } -}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/manager/messages.properties b/org.tizen.common/src/org/tizen/common/manager/messages.properties deleted file mode 100644 index 19dbd56f4..000000000 --- a/org.tizen.common/src/org/tizen/common/manager/messages.properties +++ /dev/null @@ -1 +0,0 @@ -ColorCache_0=Argument must not be null diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java b/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java deleted file mode 100644 index 97555e65e..000000000 --- a/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java +++ /dev/null @@ -1,180 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.XMLMemento;
-
-public abstract class AbstractTableModel implements ITableModel {
- private static final String TAG_ROOT = "root"; //$NON-NLS-1$
-
- private Collection<AbstractTableVO> inventory = new ArrayList<AbstractTableVO>();
- protected AbstractTableVO source;
- private boolean isDirty = false;
-
- public AbstractTableModel(AbstractTableVO source) {
- this.source = source;
-
- }
-
-
-
- public ITableVO[] getDatas() {
- if (inventory == null)
- return null;
-
- return inventory.toArray(new AbstractTableVO[inventory.size()]);
- }
-
- public void add(Collection<AbstractTableVO> datas) {
- if (datas == null)
- return;
-
- inventory.addAll(datas);
- }
-
- public int size(){
- return inventory.size();
- }
-
- public void add(AbstractTableVO data) {
- inventory.add(data);
- }
-
- public void remove(Collection<AbstractTableVO> datas) {
- if (datas == null)
- return;
-
- inventory.removeAll(datas);
- }
-
- public void remove(AbstractTableVO data) {
- inventory.remove(data);
- }
-
- public void clear() {
- inventory.clear();
- }
-
- public void load(String fileName) {
- if (inventory==null||source==null)
- return;
-
- FileReader reader = null;
- try {
- reader = new FileReader(new File(fileName));
- load(XMLMemento.createReadRoot(reader));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void load(XMLMemento memento) {
- IMemento[] children = memento.getChildren(getSourceName());
- AbstractTableVO data = null;
- String[] fields = source.getColumnNames();
- for (int i = 0; i < children.length; i++) {
- data = source.clone();
- for (int j = 0; j < fields.length; j++) {
- data.setColumnValue(j, children[i].getString(fields[j]));
- }
- add(data);
- }
- }
-
- public void save(String fileName) {
- if (inventory == null || source == null)
- return;
-
- XMLMemento memento = XMLMemento.createWriteRoot(TAG_ROOT);
- save(memento);
- FileWriter writer = null;
- try {
- writer = new FileWriter(fileName);
- memento.save(writer);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void save(XMLMemento memento) {
- Iterator<AbstractTableVO> iter = inventory.iterator();
- AbstractTableVO data = null;
- String[] fields = null;
-
- while (iter.hasNext()) {
- data = iter.next();
- fields = data.getColumnNames();
- IMemento child = memento.createChild(getSourceName());
- for (int j = 0; j < fields.length; j++) {
- child.putString(
- fields[j],
- String.valueOf(data.getColumnValue(j)));
- }
- }
-
- }
-
- public String getSourceName() {
- return this.source.getClass().getSimpleName();
- }
-
- public boolean isDirty(){
- return this.isDirty;
- }
-
- public synchronized void setDirty(boolean isDirty){
- this.isDirty = isDirty;
- }
-
-}
-
-
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java b/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java deleted file mode 100644 index 8f359a677..000000000 --- a/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java +++ /dev/null @@ -1,80 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public abstract class AbstractTableVO implements ITableVO{
- public abstract String[] getColumnNames();
- public abstract Object getColumnValue(int index);
- public abstract void setColumnValue(int index, Object value);
-
- public AbstractTableVO clone(){
- Object obj = null;
- try{
- obj = super.clone();
- }catch(CloneNotSupportedException e){
-
- }
- return (AbstractTableVO)obj;
- }
-
- public Object getColumnValue(String columnName){
- return getColumnValue(getColumnIndex(columnName));
- }
-
- public String getColumnName(int index){
- String[] columnNames = getColumnNames();
- if(index<0||index>columnNames.length)
- return null;
- else
- return columnNames[index];
- }
-
- public int getColumnIndex(String columnName){
- String[] columnNames = getColumnNames();
- int index =-1;
- for(int i=0;i<columnNames.length;i++){
- if(columnName.equals(columnNames[i])){
- index = i;
- break;
- }
- }
- return index;
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- String[] fields = getColumnNames();
- for (int j = 0; j < fields.length; j++) {
- Object obj = getColumnValue(j);
- buf.append(obj==null?"":String.valueOf(obj)); //$NON-NLS-1$
- if(j<fields.length-1)
- buf.append(","); //$NON-NLS-1$
- }
- return buf.toString();
- }
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java b/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java deleted file mode 100644 index 0282ddf99..000000000 --- a/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java +++ /dev/null @@ -1,102 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.ui.XMLMemento;
-
-public class AbstractTreeModel implements ITreeModel {
- private static final String TAG_ROOT = "root"; //$NON-NLS-1$
-
- private Collection<ITreeVO> inventory = new ArrayList<ITreeVO>();
- protected ITreeVO source;
- private boolean isDirty = false;
-
- public AbstractTreeModel(ITreeVO source){
-// if(source.getSuperclass() != ITreeVO.class)
- this.source = source;
- }
-
- public ITreeVO[] getDatas() {
- if (inventory == null)
- return null;
-
- return inventory.toArray(new ITreeVO[inventory.size()]);
- }
-
- public void add(Collection<ITreeVO> datas) {
- if (datas == null)
- return;
-
- inventory.addAll(datas);
- }
-
- public int size(){
- return inventory.size();
- }
-
- public void add(ITreeVO data) {
- inventory.add(data);
- }
-
- public void remove(Collection<ITreeVO> datas) {
- if (datas == null)
- return;
-
- inventory.removeAll(datas);
- }
-
- public void remove(ITreeVO data) {
- inventory.remove(data);
- }
-
- public void clear() {
- inventory.clear();
- }
-
- public void load(String fileName) {
- }
-
- private void load(XMLMemento memento) {
- }
-
- public void save(String fileName) {
- }
-
- private void save(XMLMemento memento) {
- }
-
- public String getSourceName() {
- return this.source.getClass().getSimpleName();
- }
-
-
-
-}
-
-
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java b/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java deleted file mode 100644 index 8a7c0f050..000000000 --- a/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java +++ /dev/null @@ -1,109 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.ArrayList;
-
-public abstract class AbstractTreeVO implements ITreeVO{
-
- private String text;
- private String description;
- private Object data = null;
- private int level = 0;
-
- private AbstractTreeVO parent;
- private ArrayList<AbstractTreeVO> children;
-
- public AbstractTreeVO(AbstractTreeVO parent,String text) {
- this.parent = parent;
- this.text = text;
- this.level = parent==null?1:parent.getLevel()+1;
- if(parent!=null)
- parent.addChild(this);
- children = new ArrayList<AbstractTreeVO>();
- }
-
- public AbstractTreeVO(AbstractTreeVO parent) {
- this(parent,null);
- }
-
- public ITreeVO[] getChildren() {
- return (ITreeVO[])children.toArray(new ITreeVO[children.size()]);
- }
-
- public ITreeVO getParent(){
- return this.parent;
- }
-
- public boolean hasChildren() {
- return children.size()>0;
- }
-
- public int size() {
- return children.size();
- }
-
- public void addChild(ITreeVO child) {
- children.add((AbstractTreeVO)child);
- }
-
- public void removeChild(Object child) {
- children.remove(child);
- }
-
- public String toString() {
- return getText();
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setData(Object data) {
- this.data = data;
- }
-
- public Object getData(){
- return this.data;
- }
-
- public int getLevel(){
- return this.level;
- }
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITableModel.java b/org.tizen.common/src/org/tizen/common/model/ITableModel.java deleted file mode 100644 index e21b41f51..000000000 --- a/org.tizen.common/src/org/tizen/common/model/ITableModel.java +++ /dev/null @@ -1,45 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.Collection;
-
-
-public interface ITableModel
-{
- public void add(AbstractTableVO datas);
- public void add(Collection<AbstractTableVO> datas);
- public void remove(AbstractTableVO datas);
- public void remove(Collection<AbstractTableVO> datas);
- public ITableVO[] getDatas();
- public void load(String fileName);
- public void save(String fileName);
- public void clear();
- public int size();
- public String getSourceName();
- public boolean isDirty();
- public void setDirty(boolean isDirty);
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITableVO.java b/org.tizen.common/src/org/tizen/common/model/ITableVO.java deleted file mode 100644 index e8a4592f3..000000000 --- a/org.tizen.common/src/org/tizen/common/model/ITableVO.java +++ /dev/null @@ -1,35 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface ITableVO extends IVO{
- public String[] getColumnNames();
- public Object getColumnValue(int index);
- public Object getColumnValue(String columnName);
- public int getColumnIndex(String columnName);
- public String getColumnName(int index);
- public void setColumnValue(int index, Object value);
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITreeVO.java b/org.tizen.common/src/org/tizen/common/model/ITreeVO.java deleted file mode 100644 index b0968aaca..000000000 --- a/org.tizen.common/src/org/tizen/common/model/ITreeVO.java +++ /dev/null @@ -1,42 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface ITreeVO extends IVO{
- public ITreeVO[] getChildren();
- public ITreeVO getParent();
- public boolean hasChildren();
- public int size();
- public void addChild(ITreeVO child);
- public void removeChild(Object child) ;
- public String getText();
- public void setText(String text);
- public String getDescription();
- public void setDescription(String description);
- public void setData(Object data);
- public Object getData();
- public int getLevel();
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/IVO.java b/org.tizen.common/src/org/tizen/common/model/IVO.java deleted file mode 100644 index c49cf134c..000000000 --- a/org.tizen.common/src/org/tizen/common/model/IVO.java +++ /dev/null @@ -1,29 +0,0 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface IVO extends Cloneable{
-}
diff --git a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties b/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties deleted file mode 100644 index c4856e3d8..000000000 --- a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties +++ /dev/null @@ -1,6 +0,0 @@ -TizenPreferencePage.0=General settings for Tizen developement: -TizenPreferencePage.1=SDK Path settings -TizenPreferencePage.2=Location: -TizenPreferencePage.3=SDK Update -TizenPreferencePage.4=Automatically find new updates and notify me - diff --git a/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java b/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java deleted file mode 100644 index d49b70804..000000000 --- a/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java +++ /dev/null @@ -1,141 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.properties; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; - -import org.tizen.common.util.DialogUtil; -import org.tizen.common.util.HostUtil; -import org.tizen.common.util.OSChecker; - - - -final public class InstallPathConfig { - - private static String sdkInstallPath; - private final static String SDKSUFFIX = ".TizenSDK"+File.separatorChar+"tizensdkpath"; - private final static String EMULATOR_PATH = "Emulator"; - private final static String INSTALLER_PATH = "InstallManager"; - - // Registry Key - private static final String REGISTRY_PATH_OF_SHELL_FOLDER = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"; - // public static final String REGISTRY_APP_DATA_OF_SHELL_FOLDER = "AppData"; - private static final String REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER = "\"Local AppData\""; - // Value Column - private static final String REG_SZ = "REG_SZ"; - - static { - // FIXME : don't need the following lines if using environment variable - String sdkPath; - - if (OSChecker.isWindows()) { - String appdataPath = getRegistryValue(REGISTRY_PATH_OF_SHELL_FOLDER,REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER) ; - sdkPath = appdataPath + File.separatorChar + SDKSUFFIX; - loadSdkPath(sdkPath); - } else if (OSChecker.isLinux() == true || OSChecker.isUnix() == true || OSChecker.isMAC() == true) { - sdkPath= System.getProperty("user.home") + File.separatorChar + SDKSUFFIX; - loadSdkPath(sdkPath); - } else { - DialogUtil.openMessageDialog(System.getProperty("os.name") + " is not supported currently."); - System.exit(0); - } - } - - public static String getEmulatorPath(){ - return sdkInstallPath + File.separatorChar + EMULATOR_PATH; - } - - /** - * @deprecated Use {@link #getSDKPath()} instead. - */ - @Deprecated - public static String getIDEPath() { - // FIXME : can't help but putting the code due to the Web IDE path , It has to be removed soon. - return System.getProperty("user.dir"); - } - - public static String getSDKPath() { - return sdkInstallPath; - } - - public static String getInstallManagerPath() { - return sdkInstallPath + File.separatorChar + INSTALLER_PATH; - } - - private static void loadSdkPath(String sdkPath) { - if (HostUtil.exists(sdkPath)) { - String[] fileContent = HostUtil.getContents(sdkPath).split("="); - if (HostUtil.exists(fileContent[1])) - sdkInstallPath = fileContent[1]; - else { - DialogUtil.openMessageDialog("Tizen SDK is not installed propertly."); - System.exit(0); - } - } else { - DialogUtil.openMessageDialog("Tizen SDK is not installed propertly."); - System.exit(0); - } - } - private static String getRegistryValue(String node, String key) { - if (!OSChecker.isWindows()) - return null; - - BufferedReader br = null; - String value = ""; - - String query = "reg query " + "\"" + node + "\" /v " + key; - try { - Process process = Runtime.getRuntime().exec(query); - String encoding = System.getProperty("sun.jnu.encoding"); - br = new BufferedReader(new InputStreamReader(process.getInputStream(), encoding)); - - String line = null; - while((line = br.readLine()) != null) { - int index = line.indexOf(REG_SZ); - if (index >= 0) { - value = line.substring(index + REG_SZ.length()).trim(); - } - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - return value; - } -}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/queue/Queue.java b/org.tizen.common/src/org/tizen/common/queue/Queue.java deleted file mode 100644 index 366aba6dd..000000000 --- a/org.tizen.common/src/org/tizen/common/queue/Queue.java +++ /dev/null @@ -1,71 +0,0 @@ -/* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ - -package org.tizen.common.queue; - -import java.util.concurrent.ConcurrentLinkedQueue; - -public class Queue<T>{ - - private ConcurrentLinkedQueue<T> queue = new ConcurrentLinkedQueue<T>(); - private boolean waiting = false; - - public synchronized void add(T e){ - queue.add(e); - if(waiting) - notify(); - } - - public synchronized T poll(){ - while (isEmpty()) { - try { - waiting = true; - wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - waiting = false; - return queue.poll(); - } - - public synchronized void clear(){ - queue.clear(); - } - - public boolean isEmpty() { - return queue.isEmpty(); - } - - public int size() { - return queue.size(); - } - - public synchronized void stop() { - if (waiting) - notify(); - } - -} diff --git a/org.tizen.common/src/org/tizen/common/swt/CommonColor.java b/org.tizen.common/src/org/tizen/common/ui/CommonColor.java index e9e9466ce..702d37745 100644 --- a/org.tizen.common/src/org/tizen/common/swt/CommonColor.java +++ b/org.tizen.common/src/org/tizen/common/ui/CommonColor.java @@ -24,20 +24,24 @@ * - S-Core Co., Ltd */ -package org.tizen.common.swt; +package org.tizen.common.ui; import org.eclipse.swt.graphics.Color; -import org.eclipse.ui.PlatformUI; +import org.tizen.common.util.cache.ColorCache; /** - * Common SWT Color + * Predefined Common SWT Color + * * @author Gyeongseok Seo <gyeongseok.seo@samsung.com> * */ public class CommonColor { - public static final Color BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0); - public static final Color RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 0); - public static final Color ORANGE_RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 69, 0); - public static final Color ROYAL_BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 65, 105, 225); - public static final Color YELLOW_GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 153, 204, 50); + public static final Color BLACK = ColorCache.getBlack(); + public static final Color RED = ColorCache.getColor( 255, 0, 0 ); + public static final Color ORANGE_RED = ColorCache.getColor( 255, 69, 0 ); + public static final Color ROYAL_BLUE = ColorCache.getColor( 65, 105, 225 ); + public static final Color YELLOW = ColorCache.getColor( 255, 255, 0 ); + public static final Color LIGHT_YELLOW = ColorCache.getColor( 255, 255, 224 ); + public static final Color YELLOW_GREEN = ColorCache.getColor( 153, 204, 50 ); + public static final Color DARK_GOLDENROD = ColorCache.getColor( 184, 134, 11 ); } diff --git a/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java b/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java new file mode 100644 index 000000000..e49672a67 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java @@ -0,0 +1,133 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.ui; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableItem; +import org.tizen.common.util.SWTUtil; + +/** + * TableToolTipListener + * + * Add tool tip to the table + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + */ +public abstract class TableToolTipListener implements Listener{ + + private Shell tip = null; + private Label label = null; + private Table table = null; + + /** + * Gets tooltip text from tableitem. + * + * @param item table item from which tooltip text is extracted. + * @return tooltip text + */ + protected abstract String getLabelText(TableItem item); + + /** + * Constructor with target table + * + * @param table will be added listener. + */ + + public void setTable(Table table) { + this.table = table; + } + + @Override + public void handleEvent(Event event) { + int eventType = event.type; + + if(SWT.MouseMove == eventType || SWT.MouseWheel == eventType || SWT.Dispose == eventType) { + if(tip != null) { + tip.dispose(); + tip = null; + label = null; + return; + } + } + if(SWT.MouseHover == eventType) { + TableItem item = this.table.getItem(new Point(event.x, event.y)); + if(item != null) { + if(tip != null && !tip.isDisposed()) { + tip.dispose(); + } + tip = new Shell(SWTUtil.getActiveShell(), SWT.ON_TOP | SWT.TOOL); + tip.setLayout(new FillLayout()); + + label = new Label(tip, SWT.None); + label.setText(this.getLabelText(item)); + label.setData(item); + + label.addListener(SWT.MouseExit, labelListener); + label.addListener(SWT.MouseDown, labelListener); + label.addListener(SWT.MouseWheel, labelListener); + + Point size = tip.computeSize(SWT.DEFAULT, SWT.DEFAULT); + Rectangle rect = item.getBounds(0); + Point pt = this.table.toDisplay(rect.x, rect.y); + tip.setBounds(pt.x, pt.y, size.x, size.y); + tip.setVisible(true); + } + } + } + + final private Listener labelListener = new Listener() { + + @Override + public void handleEvent(Event event) { + Label label = (Label)event.widget; + Shell shell = label.getShell(); + + int eventType = event.type; + if(SWT.MouseDown == eventType) { + if(table != null) { + Event e = new Event(); + e.item = (TableItem) label.getData(); + + table.setSelection((TableItem)e.item); + table.notifyListeners(SWT.Selection, e); + } + return; + } + if(SWT.MouseExit == eventType || SWT.MouseWheel == eventType) { + shell.dispose(); + return; + } + } + }; +} diff --git a/org.tizen.common/src/org/tizen/common/swt/ClosableTray.java b/org.tizen.common/src/org/tizen/common/ui/dialog/ClosableTray.java index ec149654f..34d96d075 100644 --- a/org.tizen.common/src/org/tizen/common/swt/ClosableTray.java +++ b/org.tizen.common/src/org/tizen/common/ui/dialog/ClosableTray.java @@ -23,7 +23,7 @@ * */ -package org.tizen.common.swt; +package org.tizen.common.ui.dialog; import org.eclipse.jface.action.ContributionItem; import org.eclipse.jface.action.ToolBarManager; @@ -47,6 +47,7 @@ import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; +import org.tizen.common.util.SWTUtil; /** @@ -60,7 +61,7 @@ public abstract class ClosableTray extends DialogTray { private Shell shell; private void createImages() { - Display display = Display.getCurrent(); + Display display = SWTUtil.getDisplay(); int[] shape = new int[] { 3, 3, 5, 3, 7, 5, 8, 5, 10, 3, 12, 3, 12, 5, 10, 7, 10, 8, 12, 10, 12, 12, 10, 12, 8, 10, 7, 10, 5, 12, 3, 12, 3, 10, 5, 8, 5, 7, 3, 5 @@ -169,4 +170,4 @@ public abstract class ClosableTray extends DialogTray { closeHover.dispose(); } } -}
\ No newline at end of file +} diff --git a/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java b/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java new file mode 100644 index 000000000..0229496b6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java @@ -0,0 +1,114 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.ui.dialog; + +import static org.tizen.common.util.SWTUtil.getActiveShell; +import static org.tizen.common.util.StringUtil.EMPTY_STRING; + +import org.eclipse.jface.dialogs.IInputValidator; +import org.eclipse.jface.dialogs.InputDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; + +/** + * <p> + * PasswordInputDialog. + * + * Dialog for password input + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +PasswordInputDialog +extends InputDialog +{ + /** + * Constructor with title, message + * + * @param dialogTitle title of dialog + * @param dialogMessage message of dialog + * + * @see #PasswordInputDialog(Shell, String, String) + */ + + public + PasswordInputDialog( + final String dialogTitle, + final String dialogMessage + ) + { + this( getActiveShell(), dialogTitle, dialogMessage ); + } + + /** + * Constructor with shell, title, message + * + * @param parentShell parent of dialog shell + * @param dialogTitle title of dialog + * @param dialogMessage message of dialog + * + * @see #PasswordInputDialog(Shell, String, String, IInputValidator) + */ + public + PasswordInputDialog( + final Shell parentShell, + final String dialogTitle, + final String dialogMessage + ) + { + this( parentShell, dialogTitle, dialogMessage, null ); + } + + /** + * Constructor with shell, title, message and input validator + * + * @param parentShell parent of dialog shell + * @param dialogTitle title of dialog + * @param dialogMessage message of dialog + * @param validator validator for input + */ + public + PasswordInputDialog( + final Shell parentShell, + final String dialogTitle, + final String dialogMessage, + final IInputValidator validator + ) + { + super( parentShell, dialogTitle, dialogMessage, EMPTY_STRING, validator ); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.InputDialog#getInputTextStyle() + */ + @Override + protected + int + getInputTextStyle() + { + return SWT.SINGLE | SWT.BORDER | SWT.PASSWORD; + } +}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/manager/Messages.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.java index f5fa5a835..169463a68 100644 --- a/org.tizen.common/src/org/tizen/common/manager/Messages.java +++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.java @@ -22,19 +22,24 @@ * - S-Core Co., Ltd * */ - -package org.tizen.common.manager; +package org.tizen.common.ui.page.preference; import org.eclipse.osgi.util.NLS; -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.tizen.common.manager.messages"; //$NON-NLS-1$ - public static String ColorCache_0; +public class Messages { + + private static final String BUNDLE_NAME = Messages.class.getName();//$NON-NLS-1$ + + public static String DESCRIPTION; + + public static String GROUP1; + public static String GROUP2; + + public static String LABEL_LOCATION; + public static String LABEL_UPDATE; + static { // initialize resource bundle - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { + NLS.initializeMessages( BUNDLE_NAME, Messages.class ); } } diff --git a/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties new file mode 100644 index 000000000..b26e800b8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties @@ -0,0 +1,5 @@ +DESCRIPTION=General settings +GROUP1=SDK path +LABEL_LOCATION=Location: +GROUP2=SDK update +LABEL_UPDATE=Automatically find new updates at start-up and notify me diff --git a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.java index e095402de..0672b592b 100644 --- a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.java +++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.java @@ -22,7 +22,7 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.preferences; +package org.tizen.common.ui.page.preference; import java.util.MissingResourceException; import java.util.ResourceBundle; diff --git a/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties new file mode 100644 index 000000000..d91c289b8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties @@ -0,0 +1,5 @@ +TizenPreferencePage.0=General settings +TizenPreferencePage.1=SDK path +TizenPreferencePage.2=Location: +TizenPreferencePage.3=SDK update +TizenPreferencePage.4=Automatically find new updates at start-up and notify me diff --git a/org.tizen.common/src/org/tizen/common/preferences/TizenBasePreferencePage.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/TizenBasePreferencePage.java index c90b83721..040033f9a 100644 --- a/org.tizen.common/src/org/tizen/common/preferences/TizenBasePreferencePage.java +++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/TizenBasePreferencePage.java @@ -23,7 +23,7 @@ * */ -package org.tizen.common.preferences; +package org.tizen.common.ui.page.preference; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.DirectoryFieldEditor; @@ -39,21 +39,24 @@ import org.eclipse.ui.IWorkbenchPreferencePage; import org.tizen.common.CommonPlugin; -public class TizenBasePreferencePage extends FieldEditorPreferencePage implements - IWorkbenchPreferencePage { +public class +TizenBasePreferencePage +extends FieldEditorPreferencePage +implements IWorkbenchPreferencePage +{ public final static String TIZENSDK_PATH = CommonPlugin.PLUGIN_ID + ".TizenSDKBasePreferencePage"; //$NON-NLS-1$ public static final String KEY_SDKLOCATION = "sdkpath"; //$NON-NLS-1$ public static final String KEY_SDKUPDATE = "sdkupdate"; //$NON-NLS-1$ public static final String VALUE_SDKLOCATION_DEFAULT = null;; - public static final boolean VALUE_SDKUPDATE_DEFAULT = true; + public static final boolean VALUE_SDKUPDATE_DEFAULT = false; public TizenBasePreferencePage() { //super(GRID); setPreferenceStore( CommonPlugin.getDefault().getPreferenceStore() ); //getPreferenceStore().addPropertyChangeListener( getPropertyChangeListener() ); - setDescription( PreferenceMessages.getString( "TizenPreferencePage.0" ) ); + setDescription( Messages.DESCRIPTION ); } @@ -64,7 +67,6 @@ public class TizenBasePreferencePage extends FieldEditorPreferencePage impleme @Override protected void createFieldEditors() { - // TODO Auto-generated method stub Composite composite = getFieldEditorParent(); GridLayout layout = new GridLayout(); @@ -90,16 +92,16 @@ public class TizenBasePreferencePage extends FieldEditorPreferencePage impleme } private void createPathSettingPreferences( Composite parent ) { - Composite comp = createGroup( parent, PreferenceMessages.getString( "TizenPreferencePage.1" ),1 ); //$NON-NLS-1$ + Composite comp = createGroup( parent, Messages.GROUP1, 1 ); Composite formatComposite = createCompositeEx( comp, 1, GridData.FILL_HORIZONTAL); - DirectoryFieldEditor mDirectoryField = new DirectoryFieldEditor(TizenBasePreferencePage.KEY_SDKLOCATION, PreferenceMessages.getString("TizenPreferencePage.2"), formatComposite); + DirectoryFieldEditor mDirectoryField = new DirectoryFieldEditor(KEY_SDKLOCATION, Messages.LABEL_LOCATION, formatComposite); addField(mDirectoryField); } private void createUpdateSettingPreferences( Composite parent ) { - Composite comp = createGroup( parent, PreferenceMessages.getString( "TizenPreferencePage.3" ),1 ); //$NON-NLS-1$ + Composite comp = createGroup( parent, Messages.GROUP2, 1 ); Composite formatComposite = createCompositeEx( comp, 1, GridData.FILL_HORIZONTAL); - BooleanFieldEditor startupCheckEditor = new BooleanFieldEditor(TizenBasePreferencePage.KEY_SDKUPDATE, PreferenceMessages.getString("TizenPreferencePage.4"), formatComposite); + BooleanFieldEditor startupCheckEditor = new BooleanFieldEditor(KEY_SDKUPDATE, Messages.LABEL_UPDATE, formatComposite); addField(startupCheckEditor); } diff --git a/org.tizen.common/src/org/tizen/common/swt/TrayWizardPage.java b/org.tizen.common/src/org/tizen/common/ui/page/wizard/TrayWizardPage.java index c5c328c9f..9d346fc8c 100644 --- a/org.tizen.common/src/org/tizen/common/swt/TrayWizardPage.java +++ b/org.tizen.common/src/org/tizen/common/ui/page/wizard/TrayWizardPage.java @@ -23,7 +23,7 @@ * */ -package org.tizen.common.swt; +package org.tizen.common.ui.page.wizard; import org.eclipse.jface.dialogs.DialogTray; import org.eclipse.jface.dialogs.TrayDialog; @@ -38,6 +38,7 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.tizen.common.ui.dialog.ClosableTray; /** diff --git a/org.tizen.common/src/org/tizen/common/console/AnsicodeAdapter.java b/org.tizen.common/src/org/tizen/common/ui/view/console/AnsicodeAdapter.java index 73a32ad3b..822d5ea85 100644..100755 --- a/org.tizen.common/src/org/tizen/common/console/AnsicodeAdapter.java +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/AnsicodeAdapter.java @@ -23,35 +23,58 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.console; +package org.tizen.common.ui.view.console; + +import static org.tizen.common.util.SWTUtil.getDisplay; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Map; import org.eclipse.swt.graphics.Color; -import org.eclipse.ui.PlatformUI; +import org.tizen.common.util.MapUtil; public class AnsicodeAdapter { public static final char ESCAPE = '\033'; // ANSI Escape Character that starts commands - public static final Color BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); - public static final Color RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_RED); - public static final Color GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_GREEN); - public static final Color YELLOW = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); - public static final Color BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 0,0,255); //Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); - public static final Color MAGENTA = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA); - public static final Color CYAN = new Color(PlatformUI.getWorkbench().getDisplay(), 0,255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_CYAN); - public static final Color WHITE = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); - - public static final Color INTENSE_BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY); - public static final Color INTENSE_RED = new Color(PlatformUI.getWorkbench().getDisplay(), 139, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED); - public static final Color INTENSE_GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 100, 0);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); - public static final Color INTENSE_YELLOW = new Color(PlatformUI.getWorkbench().getDisplay(), 250,250,210);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW); - public static final Color INTENSE_BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 0,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE); - public static final Color INTENSE_MAGENTA = new Color(PlatformUI.getWorkbench().getDisplay(), 139,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA); - public static final Color INTENSE_CYAN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 139, 139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_CYAN); - public static final Color INTENSE_WHITE = new Color(PlatformUI.getWorkbench().getDisplay(), 245, 245, 245);//Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + public static final Color BLACK = new Color(getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); + public static final Color RED = new Color(getDisplay(), 255, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_RED); + public static final Color GREEN = new Color(getDisplay(), 0, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_GREEN); + public static final Color YELLOW = new Color(getDisplay(), 255, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); + public static final Color BLUE = new Color(getDisplay(), 0,0,255); //Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); + public static final Color MAGENTA = new Color(getDisplay(), 255, 0, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA); + public static final Color CYAN = new Color(getDisplay(), 0,255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_CYAN); + public static final Color WHITE = new Color(getDisplay(), 255, 255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + public static final Color INTENSE_BLACK = new Color(getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY); + public static final Color INTENSE_RED = new Color(getDisplay(), 139, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED); + public static final Color INTENSE_GREEN = new Color(getDisplay(), 0, 100, 0);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); + public static final Color INTENSE_YELLOW = new Color(getDisplay(), 250,250,210);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW); + public static final Color INTENSE_BLUE = new Color(getDisplay(), 0,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE); + public static final Color INTENSE_MAGENTA = new Color(getDisplay(), 139,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA); + public static final Color INTENSE_CYAN = new Color(getDisplay(), 0, 139, 139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_CYAN); + public static final Color INTENSE_WHITE = new Color(getDisplay(), 245, 245, 245);//Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); + + public static final Map<Integer, Color[]> CODE2COLOR = Collections.unmodifiableMap( MapUtil.<Integer, Color[]>asMap( new Object[][] { + new Object[] { 30, new Color[] { INTENSE_BLACK, BLACK } }, + new Object[] { 31, new Color[] { INTENSE_RED, RED } }, + new Object[] { 32, new Color[] { INTENSE_GREEN, GREEN } }, + new Object[] { 33, new Color[] { INTENSE_YELLOW, YELLOW } }, + new Object[] { 34, new Color[] { INTENSE_BLUE, BLUE } }, + new Object[] { 35, new Color[] { INTENSE_MAGENTA, MAGENTA } }, + new Object[] { 36, new Color[] { INTENSE_CYAN, CYAN } }, + new Object[] { 37, new Color[] { INTENSE_WHITE, WHITE } }, + new Object[] { 40, new Color[] { INTENSE_BLACK, BLACK } }, + new Object[] { 41, new Color[] { INTENSE_RED, RED } }, + new Object[] { 42, new Color[] { INTENSE_GREEN, GREEN } }, + new Object[] { 43, new Color[] { INTENSE_YELLOW, YELLOW } }, + new Object[] { 44, new Color[] { INTENSE_BLUE, BLUE } }, + new Object[] { 45, new Color[] { INTENSE_MAGENTA, MAGENTA } }, + new Object[] { 46, new Color[] { INTENSE_CYAN, CYAN } }, + new Object[] { 47, new Color[] { INTENSE_WHITE, WHITE } }, + } ) ); + private static int[] commands = {'m','n'}; //SGR , DSR private static List<TextStyle> parseAnsiString(String ansiString) { @@ -148,59 +171,16 @@ public class AnsicodeAdapter { } return color; } + + + private static Color getColorFromANSICode(int code, boolean brighter) { - switch (code) { - case 30: - case 40: - if (brighter) - return INTENSE_BLACK; - else - return BLACK; - case 31: - case 41: - if (brighter) - return INTENSE_RED; - else - return RED; - case 32: - case 42: - if (brighter) - return INTENSE_GREEN; - else - return GREEN; - case 33: - case 43: - if (brighter) - return INTENSE_YELLOW; - else - return YELLOW; - case 34: - case 44: - if (brighter) - return INTENSE_BLUE; - else - return BLUE; - case 35: - case 45: - if (brighter) - return INTENSE_MAGENTA; - else - return MAGENTA; - case 36: - case 46: - if (brighter) - return INTENSE_CYAN; - else - return CYAN; - case 37: - case 47: - if (brighter) - return INTENSE_WHITE; - else - return WHITE; - default: - return null; - } + final Color[] colorSet = CODE2COLOR.get( code ); + if ( null == colorSet ) + { + return null; + } + return colorSet[brighter?0:1]; } public static String getStripAnsiString(String newLineStr) { List<TextStyle> styles = parseAnsiString(newLineStr); diff --git a/org.tizen.common/src/org/tizen/common/console/ConsoleManager.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager.java index 455d7dd7f..2c41b34f8 100644 --- a/org.tizen.common/src/org/tizen/common/console/ConsoleManager.java +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager.java @@ -23,7 +23,7 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.console; +package org.tizen.common.ui.view.console; import java.io.IOException; import java.lang.reflect.Method; @@ -48,6 +48,7 @@ import org.eclipse.ui.console.MessageConsoleStream; * @author GyeongSeok Seo {@literal <gyeongseok.seo@samsung.com>} (S-Core) */ public class ConsoleManager +implements IConsolePrinter { private IConsoleManager consoleManager; private String consoleName; @@ -248,10 +249,10 @@ public class ConsoleManager IConsoleView view = null; try { view = (IConsoleView) page.showView(id); + view.display(getConsole()); } catch (PartInitException e) { ConsolePlugin.log(e); } - view.display(getConsole()); } }; Display.getDefault().syncExec(runnable); diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java new file mode 100644 index 000000000..d9fa7f7d4 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java @@ -0,0 +1,411 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Yoonki Park <yoonki.park@samsung.com> +* Kangho Kim <kh5325.kim@samsung.com> +* BonYong Lee<bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.ui.view.console; + +import static org.tizen.common.util.SWTUtil.asyncExec; +import static org.tizen.common.util.SWTUtil.getActivePage; +import static org.tizen.common.util.SWTUtil.syncExec; +import static org.tizen.common.util.IOUtil.tryClose; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.swt.graphics.Color; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.console.ConsolePlugin; +import org.eclipse.ui.console.IConsole; +import org.eclipse.ui.console.IConsoleConstants; +import org.eclipse.ui.console.IConsoleManager; +import org.eclipse.ui.console.IConsoleView; +import org.eclipse.ui.console.MessageConsoleStream; + +/** + * ConsoleManager2. + * + * {@link MessageConsole}'s delegater + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +ConsoleManager2 +implements IConsolePrinter, IHyperlinkManager +{ + + /** + * MessageConsole to be delegated + */ + protected final MessageConsoleSpy console; + + /** + * Link manager + */ + protected final HyperlinkManager hyperlinkManager; + + /** + * console's name + * + * @see {@link IConsole#setName(String)} + */ + private String consoleName; + + /** + * document model's virtual length + */ + protected int documentLength = 0; + + /** + * Constructs a new console manager. + * + * @param consoleName - the key title + * @param focus - true if focus on console, false if not + */ + public + ConsoleManager2( + final String consoleName, + final boolean focus + ) + { + this.console = createMessageConsole(); + this.hyperlinkManager = new HyperlinkManager( console ); + this.console.getDocument().addDocumentListener( hyperlinkManager ); + + if ( focus ) + { + getConsoleManager().showConsoleView(console); + } + + setName( consoleName ); + } + + /** + * return {@link IConsoleManager} from {@link ConsolePlugin} + * + * @return {@link IConsoleManager} + * + * @see ConsolePlugin#getConsoleManager() + */ + protected IConsoleManager getConsoleManager() + { + return ConsolePlugin.getDefault().getConsoleManager(); + } + + /** + * return <code>IConsole</code>s to be attached to {@link IConsoleManager} + * + * @return <code>IConsole</code>s + * + * @see #getConsoleManager() + * @see IConsoleManager#getConsoles() + */ + protected IConsole[] getConsoles() + { + return getConsoleManager().getConsoles(); + } + + + /** + * Change Console Name. + * + * @param newName - console Title. It shown console's tab bar. + * @author Gyeongseok.seo@samsung.com + */ + public void + setName( + final String newName + ) + { + if ( null == newName ) + { + throw new NullPointerException(); + } + this.consoleName = newName; + asyncExec( new Runnable() + { + public void run() + { + if ( null == console ) + { + return ; + } + console.setName(newName); + } + } ); + } + + /** + * Create message console + * + * @return Message console for emulator + */ + synchronized protected MessageConsoleSpy createMessageConsole() + { + // Delete Old Console from console view + final IConsole[] consoles = getConsoles(); + for ( int i = 0, n = consoles.length ; i < n ; ++i ) + { + if ( !this.consoleName.equals(consoles[i].getName() ) ) + { + continue; + } + getConsoleManager().removeConsoles( new IConsole[] { console } ); + } + + final MessageConsoleSpy console = new MessageConsoleSpy( this.consoleName ); + getConsoleManager().addConsoles( new IConsole[] { console } ); + + return console; + } + + /** + * return {@link IConsole} + * + * @return {@link IConsole} to be managed + */ + protected IConsole getConsole() { + return this.console; + } + + /** + * print <code>line</code> out to {@link IConsole} with line separator + * + * @param line text to print + */ + synchronized public void println(String line) { + final MessageConsoleStream output = createConsoleStream(); + + try + { + output.println( line ); + documentLength += ( line.length() + 1 ); + + } finally + { + tryClose( output ); + } + } + + /** + * Print out using {@link Process} + * @param process + */ + public void printProcessStreams( final Process process) { + + clear(); + // waitAndRead while process is running + ConsoleProcessClosure closure = new ConsoleProcessClosure(process, this); + + closure.runBlocking(); // a blocking cal + } + + + /** + * Return configured <code>MessageConsoleStream</code> + * + * with <code>fontStyle</code> and <code>color</code> + * + * @param fontStyle SWT font style like {@link SWT#BOLD}, {@link SWT#ITALIC}, and etc. + * @param color color of message to be printed + * + * @return configured <code>MessageConsoleStream</code> + * + * @see #configureConsole(MessageConsoleStream, int, Color) + */ + protected + MessageConsoleStream + getConsoleStream( + final int fontStyle, + final Color color + ) + { + final MessageConsoleStream stream = createConsoleStream(); + + configureConsole( stream, fontStyle, color ); + + return stream; + } + + + /** + * Factory method for <code>MessageConsoleStream</code> + * + * @return <code>MessageConsoleStream</code> to be created + * + * @see MessageConsole#newMessageStream() + */ + protected + MessageConsoleStream + createConsoleStream() + { + final MessageConsoleStream stream = console.newMessageStream(); + + return stream; + } + + /** + * Configure <code>stream</code> with <code>fontStyle</code> and <code>color</code> + * + * @param stream <code>MessageConsoleStream</code> to configure + * @param fontStyle SWT font style + * @param color + * + * @see SWT#NORMAL + * @see SWT#BOLD + * @see SWT#ITALIC + */ + protected void + configureConsole( + final MessageConsoleStream stream, + final int fontStyle, + final Color color + ) + { + syncExec( new Runnable() + { + public void run() + { + // font setting + stream.setFontStyle( fontStyle ); + + // color setting + stream.setColor( color ); + } + } ); + } + + /** + * print out <code>message</code> with <code>fontStyle</code> and <code>color</code> + * + * @param message message to print out + * @param fontStyle SWT font style + * @param color color of message + */ + synchronized public + void + print( + final String message, + final int fontStyle, + final Color color + ) + { + final MessageConsoleStream stream = getConsoleStream( fontStyle, color ); + try + { + stream.print(message); + documentLength += (message.length() ); + } + finally + { + tryClose( stream ); + } + } + + /** + * print out with line separator + * + * @param message message to print out + * @param fontStyle font style + * @param color color + * + * @see #print(String, int, Color) + */ + public + void + println( + final String message, + final int fontStyle, + final Color color + ) + { + print( message + "\n", fontStyle, color ); + } + + /** + * clear message console + */ + synchronized public + void + clear() + { + syncExec( + new Runnable() { + public void run() { + IDocument document = console.getDocument(); + if ( null == document ) + { + return ; + } + document.set(""); + } + } + ); + documentLength = 0; + } + + /** + * Activate console + */ + public + void + show() + { + syncExec( + new Runnable() { + public void run() { + final IWorkbenchPage page = getActivePage(); + if ( null == page ) + { + // How to handle no active page( no view page ) + throw new IllegalStateException(); + } + try { + IConsoleView view = (IConsoleView) page.showView( IConsoleConstants.ID_CONSOLE_VIEW ); + view.display(getConsole()); + } catch ( + final PartInitException e + ) + { + ConsolePlugin.log(e); + } + } + } + ); + } + + /* (non-Javadoc) + * @see org.tizen.common.console.IHyperlinkerManager#addLinker(org.tizen.common.console.LinkInfo) + */ + @Override + public + void + addLinker( + final LinkInfo link + ) + { + hyperlinkManager.addLinker( link ); + } + +} + diff --git a/org.tizen.common/src/org/tizen/common/console/ConsoleProcessClosure.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleProcessClosure.java index a9fa6ed0f..c82224da6 100644 --- a/org.tizen.common/src/org/tizen/common/console/ConsoleProcessClosure.java +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleProcessClosure.java @@ -23,9 +23,12 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.console; +package org.tizen.common.ui.view.console; + +import static org.tizen.common.util.IOUtil.tryClose; import java.io.BufferedReader; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -44,16 +47,18 @@ public class ConsoleProcessClosure { * Thread which continuously reads from a input stream and pushes the read * data to an output stream which is immediately flushed afterwards. */ - protected static class ReaderThread extends Thread { + protected static class ReaderThread + extends Thread + implements Closeable { private InputStream fInputStream; - private ConsoleManager fConsole; + private IConsolePrinter fConsole; private boolean fFinished = false; private String lineSeparator; /* * outputStream can be null */ - public ReaderThread(ThreadGroup group, String name, InputStream in, ConsoleManager out) { + public ReaderThread(ThreadGroup group, String name, InputStream in, IConsolePrinter out) { super(group, name); fConsole = out; fInputStream = in; @@ -82,11 +87,7 @@ public class ConsoleProcessClosure { } catch (IOException x) { // ignore } finally { - try { - fInputStream.close(); - } catch (IOException e) { - // ignore - } + tryClose( fInputStream ); } } finally { complete(); @@ -124,7 +125,7 @@ public class ConsoleProcessClosure { protected static int fCounter = 0; protected Process fProcess; - protected ConsoleManager fConsole; + protected IConsolePrinter fConsole; protected ReaderThread fOutputReader; protected ReaderThread fErrorReader; @@ -140,7 +141,7 @@ public class ConsoleProcessClosure { * prcess stderr is written to this stream. Can be * <code>null</code>, if not interested in reading the output */ - public ConsoleProcessClosure(Process process, ConsoleManager console) { + public ConsoleProcessClosure(Process process, IConsolePrinter console) { fProcess = process; fConsole = console; } @@ -189,8 +190,7 @@ public class ConsoleProcessClosure { fErrorReader.waitFor(); } - fOutputReader.close(); - fErrorReader.close(); + tryClose( fOutputReader, fErrorReader ); // it seems that thread termination and stream closing is working // without // any help @@ -205,10 +205,7 @@ public class ConsoleProcessClosure { return true; } fProcess = null; - fOutputReader.close(); - fErrorReader.close(); - fOutputReader = null; - fErrorReader = null; + tryClose( fOutputReader, fErrorReader ); } return false; } @@ -241,10 +238,7 @@ public class ConsoleProcessClosure { if (!fErrorReader.finished()) { fErrorReader.waitFor(); } - fOutputReader.close(); - fErrorReader.close(); - fOutputReader = null; - fErrorReader = null; + tryClose( fOutputReader, fErrorReader ); } } diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java b/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java new file mode 100644 index 000000000..be32de9b1 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java @@ -0,0 +1,131 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.ui.view.console; + +import java.util.Iterator; +import java.util.TreeSet; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DocumentEvent; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentListener; +import org.eclipse.ui.console.TextConsole; + +/** + * HyperlinkManager. + * + * Manage hyperlink. + * + * process deferedly because {@link TextConsole} is asynchronous. + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +HyperlinkManager +implements IHyperlinkManager, IDocumentListener +{ + /** + * {@link TextConsole} to connect link + */ + protected TextConsole console; + + /** + * unconnected links + */ + protected final TreeSet<LinkInfo> dangledLinks = new TreeSet<LinkInfo>(); + + /** + * Constructor with {@link TextConsole} to connect link + * + * @param console {@link TextConsole} to connect link + */ + public + HyperlinkManager( + final TextConsole console + ) + { + this.console = console; + } + + /* (non-Javadoc) + * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) + */ + @Override + public + void + documentAboutToBeChanged( + final DocumentEvent event + ) + { + // Not implement + } + + /* (non-Javadoc) + * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) + */ + @Override + public + void + documentChanged( + final DocumentEvent event + ) + { + final IDocument doc = event.getDocument(); + final int docLen = doc.getLength(); + + for ( final Iterator<LinkInfo> iter = dangledLinks.iterator() ; iter.hasNext() ; ) + { + final LinkInfo info = iter.next(); + + if ( docLen < info.getEnd() ) + { + return ; + } + + try + { + this.console.addHyperlink( info.getLink(), info.getStart(), info.getLength() ); + iter.remove(); + } catch ( final BadLocationException e ) + { + e.printStackTrace(); + } + } + } + + /* (non-Javadoc) + * @see org.tizen.common.console.IHyperlinkerManager#addLinker(org.tizen.common.console.LinkInfo) + */ + @Override + public + void + addLinker( + final LinkInfo link + ) + { + dangledLinks.add( link ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java b/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java new file mode 100644 index 000000000..efa154ac7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java @@ -0,0 +1,46 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.ui.view.console; + +import org.eclipse.swt.graphics.Color; + +/** + * IConsolePrinter. + * + * {@link IConsoleManager}'s adaptation interface + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface IConsolePrinter +{ + /** + * print line out to {@link IConsole} + * + * @param msg message to print out + * @param fontStyle font style flag + * @param color foreground color of <code>msg</code> to print out + */ + void print( String msg, int fontStyle, Color color ); +} diff --git a/org.tizen.common/src/org/tizen/common/control/NotSupportedTypeException.java b/org.tizen.common/src/org/tizen/common/ui/view/console/IHyperlinkManager.java index 64cfa87c8..68d995e6f 100644 --- a/org.tizen.common/src/org/tizen/common/control/NotSupportedTypeException.java +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/IHyperlinkManager.java @@ -4,7 +4,7 @@ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. * * Contact: -* Kangho Kim <kh5325.kim@samsung.com> +* BonYong Lee <bonyong.lee@samsung.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,25 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.control; +package org.tizen.common.ui.view.console; -public class NotSupportedTypeException extends Exception { - public NotSupportedTypeException(){ - super(); - } - public NotSupportedTypeException(String message){ - super(message); - } +/** + * IHyperlinkerManager. + * + * Manage hyperlinks in asynchronous stream + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public interface +IHyperlinkManager +{ + /** + * add <code>link</code> to IConsole + * + * @param link hyper link's info + * + * @see LinkInfo + */ + void addLinker( LinkInfo link ); } diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java b/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java new file mode 100644 index 000000000..9eb0bbcaa --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java @@ -0,0 +1,151 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.ui.view.console; + +import org.eclipse.ui.console.IHyperlink; + +/** + * LinkInfo. + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +LinkInfo +implements Comparable<LinkInfo> +{ + /** + * Link's start offset + */ + protected final int offset; + + /** + * Link's textual length + */ + protected final int length; + + /** + * <code>IHyperlink</code> to connect + */ + protected final IHyperlink link; + + /** + * Constructor with link's offset, length and hyperlink + * + * @param offset link's start offset + * @param length link's length + * @param link hyperlink + */ + public LinkInfo( + final int offset, + final int length, + final IHyperlink link + ) + { + this.offset = offset; + this.length = length; + this.link = link; + if ( length < 0 ) + { + throw new IllegalArgumentException( "Link's length is negative :" + this ); + } + } + + /** + * Return link's start position in text + * + * @return link's start position + * + * @see #getEnd() + * @see #getLength() + */ + public + int + getStart() + { + return this.offset; + } + + /** + * Return link's end position in text + * + * @return link's end position + * + * @see #getStart() + * @see #getEnd() + */ + public + int + getEnd() + { + return getStart() + getLength(); + } + + /** + * Return link's length + * + * @return link's length + * + * @see #getStart(); + * @see #getEnd(); + */ + public + int + getLength() + { + return this.length; + } + + /** + * return hyper link + * @return {@link IHyperlink} + */ + public + IHyperlink + getLink() + { + return this.link; + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public + int + compareTo(LinkInfo o) + { + return getLength() - o.getLength(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + return "Link(" + getStart() + ":" + getEnd() + ")-" + link; + } +} diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java b/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java new file mode 100644 index 000000000..1a1a7dfd6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java @@ -0,0 +1,55 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.ui.view.console; + +import org.eclipse.ui.console.MessageConsole; + +public class +MessageConsoleSpy +extends MessageConsole +{ + + /** + * Constructor with console name + * + * @param name console's key title + */ + public MessageConsoleSpy( final String name ) + { + super( name, null ); + } + + /** + * make {@link AbstractConsole#setName(String)} accessible + * + * @see org.eclipse.ui.console.AbstractConsole#setName(java.lang.String) + */ + public void setName( final String name ) + { + super.setName( name ); + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/console/TextStyle.java b/org.tizen.common/src/org/tizen/common/ui/view/console/TextStyle.java index d068ef8bf..000c1b0ab 100644 --- a/org.tizen.common/src/org/tizen/common/console/TextStyle.java +++ b/org.tizen.common/src/org/tizen/common/ui/view/console/TextStyle.java @@ -23,7 +23,7 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.console; +package org.tizen.common.ui.view.console; import org.eclipse.swt.graphics.Color; diff --git a/org.tizen.common/src/org/tizen/common/swt/PictureLabel.java b/org.tizen.common/src/org/tizen/common/ui/widget/PictureLabel.java index 1cda75f87..c56ed6292 100644 --- a/org.tizen.common/src/org/tizen/common/swt/PictureLabel.java +++ b/org.tizen.common/src/org/tizen/common/ui/widget/PictureLabel.java @@ -23,7 +23,7 @@ *
*/
-package org.tizen.common.swt;
+package org.tizen.common.ui.widget;
import java.util.List;
import java.util.ArrayList;
@@ -191,6 +191,9 @@ public class PictureLabel extends Canvas { }
class ImageClickedEvent extends java.util.EventObject {
+
+ private static final long serialVersionUID = 2923125560667763769L;
+
public int x, y;
public ImageClickedEvent(Object source, int x, int y) {
diff --git a/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties b/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties deleted file mode 100644 index 06a30a973..000000000 --- a/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties +++ /dev/null @@ -1,3 +0,0 @@ -## -message.dialogTitle = Tizen SDK -message.askForUpdate = Updates are available for Tizen SDK. Do you want to install them?
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java b/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java new file mode 100755 index 000000000..ee1a5715d --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java @@ -0,0 +1,1124 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * ArrayUtil. + * + * Helper related to array + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class ArrayUtil +{ + /** + * Empty {@link Object} array + */ + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + + + /** + * <p> + * check <code>collection</code> has no element. + * + * use without null check. + * + * Old style + * + * <pre> + * Object[] array = null; + * ... + * if ( null != array && 0 < array.length ) { + * ... + * } + * </pre> + * + * Usage : + * <p> + * + * <pre> + * Object[] array = null; + * ... + * if ( !ArrayUtil.isEmpty( array ) ) { + * ... + * } + * </pre> + * + * or "import static" style if you use JDK6 + * + * </pre> + * import static org.tizen.common.util.CollectionUtil.isEmpty; + * ... + * + * Object[] array = null; + * ... + * if ( !isEmpty( array ) ) { + * ... + * } + * </pre> + * + * @param array {@link Collection} to check + * + * @return value if collection is empty + */ + public static <T> + boolean + isEmpty( + final T[] array + ) + { + if ( null == array ) + { + return true; + } + + return (0 == array.length); + } + + /** + * <p> + * Return first element in <code>array</code><br> + * + * Return <code>null</code> if <code>array</code> is null or empty + * </p> + * + * @param <T> type of element in <code>array</code> + * @param array object array to check + * + * @return first elemtn in <code>array</code> + */ + public static <T> + T + pickupFirst( T[] array ) + { + if ( isEmpty( array ) ) + { + return null; + } + + return array[0]; + } + + /** + * <p> + * Return last element in <code>array</code><br> + * + * Return <code>null</code> if <code>array</code> is null or empty + * </p> + * + * @param <T> type of element in <code>array</code> + * @param array object array to check + * + * @return last elemtn in <code>array</code> + */ + public static <T> + T + pickupLast( T[] array ) + { + if ( isEmpty( array ) ) + { + return null; + } + + return array[array.length - 1]; + } + + /** + * Create array with <code>length</code> + * + * @param <T> type of element in array to create + * @param type {@link Class} + * @param length array size + * + * @return created array + */ + @SuppressWarnings("unchecked") + public static <T> + T[] newArray( Class<? extends T> type, int length) + { + return (T[]) Array.newInstance( type, length); + } + + /** + * {@link Iterator} for array + * + * @param <K> element type in array + */ + public static class + ArrayIterator<K> + implements Iterator<K> + { + /** + * cloned array + */ + protected final K[] objs; + + /** + * original array + */ + protected final K[] origin; + + /** + * current element index + */ + protected int index = 0; + + /** + * Constructor with array + * + * @param objs array to iterate + */ + public + ArrayIterator( + final K[] objs + ) + { + this.origin = objs; + + this.objs = ( null == origin )?null:origin.clone(); + } + + /* (non-Javadoc) + * @see java.util.Iterator#hasNext() + */ + @Override + public + boolean + hasNext() + { + if ( null == this.objs ) + { + return false; + } + return ( index < this.objs.length ); + } + + /* (non-Javadoc) + * @see java.util.Iterator#next() + */ + @Override + public + K + next() + { + if ( null == this.objs ) + { + throw new NoSuchElementException(); + } + if ( this.objs.length <= index ) + { + throw new NoSuchElementException(); + } + + if ( objs[index] != origin[index] ) { + throw new ConcurrentModificationException(); + } + return this.objs[index++]; + } + + /* (non-Javadoc) + * @see java.util.Iterator#remove() + */ + @Override + public + void + remove() + { + throw new UnsupportedOperationException(); + } + + } + + /** + * Create and return {@link Iterator} for <code>array</code> + * + * @param <T> iteraing element's type + * @param array array to iterate + * + * @return {@link Iterator} for <code>array</code> + */ + public static <T> Iterator<T> iterator( final T[] array ) + { + return new ArrayIterator<T>( array ); + } + + /** + * <p> + * run <code>runner</code> iterateing element of <code>array</code>. + * + * use without null-check for <code>array</code> + * + * delegate error handling to <code>array</code> + * </p> + * + * <pre> + * + * ArrayUtil.iterate( + * Arrays.asList( "hello", "Hello", "World", null, "Test" ), + * new IteratingRunner<String>() { + * public void run( String arg ) { + * ... + * } + * } + * ); + * + * </pre> + * + * @param <T> type of element in <code>array</code> + * @param array array containing element + * @param runner {@link Runnable} to execute + * + * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception + * + * @see {@link #iterate(Object[], IteratingRunner, boolean)} + * @see FilterIterator + */ + public static <T> + void + iterate( + final T[] array, + final IteratingRunner<T> runner + ) + { + try + { + iterate( array, runner, true ); + } catch ( final InvocationTargetException e) + { + // Be never reached + throw new IllegalStateException( e ); + } + } + + /** + * <p> + * run <code>runner</code> iterateing element of <code>array</code>. + * + * use without null-check for <code>array</code> + * + * delegate error handling to <code>runner</code> + * + * </p> + * <pre> + * + * ArrayUtil.iterate( + * Arrays.asList( "hello", "Hello", "World", null, "Test" ), + * new IteratingRunner<String>() { + * public void run( String arg ) { + * ... + * } + * }, + * true + * ); + * + * </pre> + * + * @param <T> type of element in <code>array</code> + * @param array array containing element + * @param runner {@link Runnable} to execute + * @param bForceProcess flag to iterate continuously when exception occurs + * + * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception + * + * @see FilterIterator + */ + public static <T> + void + iterate( + final T[] array, + final IteratingRunner<T> runner, + final boolean bForceProcess + ) + throws InvocationTargetException + { + if ( null == runner ) + { + return ; + } + + for ( final T arg : safe( array ) ) + { + if ( null == arg && !bForceProcess ) + { + continue ; + } + try + { + runner.run( arg ); + } catch ( Throwable e ) + { + if ( !bForceProcess ) + { + throw new InvocationTargetException( e ); + } + } + } + } + + /** + * <p> + * Fiter <code>array</code> and return filtered array + * + * Ignore exception in filtering logic + * </p> + * + * @param <T> type of element in <code>array</code> + * @param array array to filter + * @param runner object to determine if filter + */ + public static <T> + T[] + filter( + final T[] array, + final IteratingAcceptor<T> runner + ) + { + try + { + return filter( array, runner, true ); + } catch ( final InvocationTargetException e ) + { + // Be never reached + throw new IllegalStateException( e ); + } + } + /** + * <p> + * Fiter <code>array</code> and return filtered array + * + * determined if stop or keep going using <code>bForceProcess</code> in case of exception. + * </p> + * + * @param <T> type of element in <code>array</code> + * @param array array to filter + * @param runner object to determine if filter + * @param bForceProcess flag to keep going when exception occurs + * + * @throws InvocationTargetException when <code>runner</code>'s {@link IteratingAcceptor#accept(Object)} throws exception + */ + @SuppressWarnings("unchecked") + public static <T> + T[] + filter( + final T[] array, + final IteratingAcceptor<T> runner, + final boolean bForceProcess + ) throws InvocationTargetException + { + final ArrayList<T> list = new ArrayList<T>(); + + for ( final T arg : safe( array ) ) + { + if ( null == arg && !bForceProcess ) + { + continue ; + } + try + { + if ( runner.accept( arg ) ) + { + list.add( arg ); + } + } catch ( Throwable e ) + { + if ( !bForceProcess ) + { + throw new InvocationTargetException( e ); + } + } + + } + + return (T[]) list.toArray( newArray( array.getClass().getComponentType(), list.size() ) ); + } + + + /** + * Convert <code>source</code> to {@link Object[]} + * + * throw {@link IllegalArgumentException} if source is not array type + * + * @param source object to convert + * + * @return object to converted + */ + public static + Object[] + toObjectArray( + final Object source + ) + { + if ( source instanceof Object[] ) + { + return ( Object[] )source; + } + + if ( null == source ) + { + return EMPTY_OBJECT_ARRAY; + } + + if ( !source.getClass().isArray() ) + { + throw new IllegalArgumentException( "source must be an array"); + } + + final int length = Array.getLength( source ); + if ( 0 == length ) + { + return EMPTY_OBJECT_ARRAY; + } + + Class<?> wrapperType = null; + for ( int i = 0 ; null == wrapperType && i < length ; ++i ) + { + Object obj = Array.get( source, 0 ); + if ( null == obj ) + { + continue; + } + wrapperType = obj.getClass(); + } + if ( null == wrapperType ) + { + return (Object[]) source; + } + + final Object[] newArray = + (Object[]) Array.newInstance( wrapperType, length ); + for( int i=0 ; i<length ; ++i ) + { + newArray[i] = Array.get( source, i ); + } + + return newArray; + } + + /** + * Return size if object is array or {@link Collection} + * + * Return <code>0</code> in case of the other type + * + * @param obj object to check + * + * @return size + */ + public static + int + size( + final Object obj + ) + { + if ( obj instanceof Object[] ) + { + return size( ( Object[] ) obj ); + } + else if ( obj instanceof boolean[] ) + { + return size( ( boolean[] ) obj ); + } + else if ( obj instanceof byte[] ) + { + return size( ( byte[] )obj ); + } + else if ( obj instanceof char[] ) + { + return size( ( char[] ) obj ); + } + else if ( obj instanceof short[] ) + { + return size( ( short[] )obj ); + } + else if ( obj instanceof int[] ) + { + return size( (int[] ) obj ); + } + else if ( obj instanceof long[] ) + { + return size( ( long[] ) obj ); + } + else if ( obj instanceof float[] ) + { + return size( (float[] ) obj ); + } + else if ( obj instanceof double[] ) + { + return size( ( double[] ) obj ); + } + else if ( obj instanceof Collection ) + { + return CollectionUtil.size( (Collection<?>) obj ); + } + return 0; + + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs boolean array object + * + * @return size of array + */ + public static + int + size( + final boolean[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs byte array object + * + * @return size of array + */ + public static + int + size( + final byte[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs char array object + * + * @return size of array + */ + public static + int + size( + final char[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs short array object + * + * @return size of array + */ + public static + int + size( + final short[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs int array object + * + * @return size of array + */ + public static + int + size( + final int[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs long array object + * + * @return size of array + */ + public static + int + size( + final long[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs float array object + * + * @return size of array + */ + public static + int + size( + final float[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param objs double array object + * + * @return size of array + */ + public static + int + size( + final double[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * Return <code>objs</code>'s length + * + * Return 0 if <code>objs</code> is null. + * + * @param <T> type of array + * @param objs T type array object + * + * @return size of array + */ + public static <T> + int + size( + final T[] objs + ) { + if ( null == objs ) + { + return 0; + } + return objs.length; + } + + /** + * add <code>obj</code> to <code>array</code> + * + * Return array having only <code>obj</code> if <code>array</code> is <code>null</code> + * + * @param array array to add element + * @param obj new element to add + * + * @return added array + */ + @SuppressWarnings("unchecked") + public static <T> T[] + add( + final T[] array, + final T obj + ) + { + Class<?> compType = Object.class; + if ( null != array ) + { + compType = array.getClass().getComponentType(); + } + else if ( null != obj ) + { + compType = obj.getClass(); + } + + final int newArrLength = size( array ) + 1; + final T[] newArr = + (T[]) Array.newInstance( compType, newArrLength ); + + if ( null != array ) + { + System.arraycopy( array, 0, newArr, 0, array.length ); + } + newArr[newArrLength - 1] = obj; + return newArr; + } + + /** + * remove elements whose index is between <code>startIndex</code> and <code>endIndex</code> + * + * and return applied array + * + * @param <T> type of array element + * @param array array to remove elements + * @param startIndex start index of range to remove + * @param endIndex end index of range to remove + * + * @return change applied new array + * + * @throws ArrayIndexOutOfBoundsException + * if <code>startIndex</code> or <code>endIndex</code> is not in range of array + * @throws IllegalArgumentException + * if <code>startIndex</code> is greater than <code>endIndex</code> + */ + @SuppressWarnings("unchecked") + public static <T> T[] + remove( + final Object[] array, + final int start, + final int end + ) + { + if ( null == array ) + { + throw new NullPointerException(); + } + Assert.isTrue( + start <= end, + "start indnex(" + start + ") is greater than end index(" + end + ")" + ); + + int startIndex = Math.max( 0, start ); + int endIndex = Math.min( array.length, end ); + if ( endIndex <= startIndex ) + { + return (T[]) array; + } + + final Class<?> compType = array.getClass().getComponentType(); + + final int removeSize = endIndex - startIndex; + + final int newArrLength = size( array ) - removeSize; + + final Object[] newArr = + (Object[]) Array.newInstance( compType, newArrLength ); + + System.arraycopy( array, 0, newArr, 0, startIndex ); + System.arraycopy( array, endIndex, newArr, startIndex, array.length-endIndex ); + + return (T[]) newArr; + } + + /** + * remove elements whose index is <code>index</code> + * + * and return applied array + * + * @param <T> type of array element + * @param array array to remove elements + * @param index index to remove + * + * @return change applied new array + * + * @throws ArrayIndexOutOfBoundsException + * if <code>index</code> is not in range of array + */ + public static <T> T[] + remove( + final Object[] array, + final int index + ) + { + return remove( array, index, index + 1); + } + + /** + * Check if <code>array</code> contains <code>element</code> + * + * @param array array to check + * @param element object to check + * + * @return <code>true</code> if <code>collection</code> contain <code>element</code> + */ + public static <K, V> + boolean + contains( + final K[] array, + final V element + ) + { + if ( null == array ) + { + return false; + } + + for ( final Object candidate : array ) + { + if ( ObjectUtil.equals( candidate, element ) ) + { + return true; + } + } + return false; + } + + /** + * Return <code>index</code> th element in <code>collection</code> + * + * Return <code>null</code> if <code>index</code> is out of range + * + * @param <K> array type + * @param array array object to access + * @param index array index + * @return <code>index</code> th element in array + */ + public static <K> + K + get( + final K[] array, + final int index + ) + { + if ( null == array ) + { + return null; + } + if ( index < 0 ) + { + return null; + } + if ( array.length <= index ) + { + return null; + } + + return array[index]; + } + + /** + * Convert <code>array</code> to {@link Boolean[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Boolean[] convertToWrapper( final boolean[] array ) + { + final int nArray = size( array ); + final Boolean[] ret = new Boolean[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Byte[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Byte[] convertToWrapper( final byte[] array ) + { + final int nArray = size( array ); + final Byte[] ret = new Byte[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Character[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Character[] convertToWrapper( final char[] array ) + { + final int nArray = size( array ); + final Character[] ret = new Character[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + + /** + * Convert <code>array</code> to {@link Short[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Short[] convertToWrapper( final short[] array ) + { + final int nArray = size( array ); + final Short[] ret = new Short[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Integer[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Integer[] convertToWrapper( final int[] array ) + { + final int nArray = size( array ); + final Integer[] ret = new Integer[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Long[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Long[] convertToWrapper( final long[] array ) + { + final int nArray = size( array ); + final Long[] ret = new Long[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Float[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Float[] convertToWrapper( final float[] array ) + { + final int nArray = size( array ); + final Float[] ret = new Float[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + /** + * Convert <code>array</code> to {@link Double[]} + * + * @param array array to convert + * + * @return converted array + */ + public static Double[] convertToWrapper( final double[] array ) + { + final int nArray = size( array ); + final Double[] ret = new Double[nArray]; + + for ( int i = 0 ; i < nArray ; ++i ) + { + ret[i] = array[i]; + } + + return ret; + } + + @SuppressWarnings("unchecked") + public static <T> T[] safe( T[] unsafe ) + { + return (T[]) ObjectUtil.nvl( unsafe, EMPTY_OBJECT_ARRAY ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/Assert.java b/org.tizen.common/src/org/tizen/common/util/Assert.java new file mode 100755 index 000000000..b9c4a0af7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/Assert.java @@ -0,0 +1,837 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import java.text.MessageFormat; +import java.util.Collection; +import java.util.Map; + +/** + * Assert + * + * Helper for assertion + * + * Assert following + * <ul> + * <li>boolean expression</li> + * <li>null object</li> + * <li>object equality</li> + * <li>string</li> + * <li>Collection</li> + * <li>Map</li> + * <li>object type</li> + * </ul> + */ +public class +Assert +{ + protected Assert() { } + + /** + * Encapsulated method in case of failure in assertion + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message. + * + * @param msg exception's message to throw + */ + public static + void + fail( + final Object msg + ) + { + if ( msg instanceof String ) + { + throw new IllegalArgumentException( (String) msg ); + } else if ( null != msg ) + { + throw new IllegalArgumentException( msg.toString() ); + } + } + + /** + * Assert that <code>exp</code> is <code>true</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>exp</code> is <code>false</code> + * + * @param exp boolean value to check + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + isTrue( + final boolean exp, + final String msg + ) + { + if ( exp ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>exp</code> is <code>false</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>exp</code> is <code>true</code> + * + * @param exp boolean value to check + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + isFalse( + final boolean exp, + final String msg + ) + { + if ( !exp ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>exp</code> is <code>true</code> + * + * Throw {@link IllegalArgumentException} with "Expression must be true" message + * + * if <code>exp</code> is <code>false</code> + * + * @param exp boolean value to check + * + * @see #isTrue(boolean, String) + */ + public static void + isTrue( + final boolean exp + ) + { + isTrue( exp, "Expression must be true" ); + } + + /** + * Assert that <code>exp</code> is <code>false</code> + * + * Throw {@link IllegalArgumentException} with "Expression must be false" message + * + * if <code>exp</code> is <code>true</code> + * + * @param exp boolean value to check + * + * @see #isFalse(boolean, String) + */ + public static + void + isFalse( + final boolean exp + ) + { + isFalse( exp, "Expression must be false" ); + } + + /** + * Assert that <code>obj</code> is <code>null</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>obj</code> is not <code>null</code> + * + * @param obj object to check + * @param msg exception's message to throw + * + * @see #isTrue(boolean, String) + */ + public static + void + isNull( + final Object obj, + final String msg + ) + { + isTrue( null == obj, msg ); + } + + /** + * Assert that <code>obj</code> is <code>null</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>obj</code> is <code>null</code> + * + * @param obj object to check + * @param msg exception's message to throw + * + * @see #isFalse(boolean, String) + */ + public static + void + notNull( + final Object obj, + final String msg + ) + { + isFalse( null == obj, msg ); + } + + /** + * Assert that <code>obj</code> is <code>null</code> + * + * Throw {@link IllegalArgumentException} with "Object must be null" message + * + * if <code>obj</code> is not <code>null</code> + * + * @param obj object to check + * + * @see #isNull(Object, String) + */ + public static + void + isNull( + final Object obj + ) + { + isNull( obj, "Object must be null" ); + } + + /** + * Assert that <code>obj</code> is not <code>null</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>obj</code> is <code>null</code> + * + * @param obj object to check + * + * @see #notNull(Object, Object) + */ + public static + void + notNull( + final Object obj + ) + { + notNull( obj, "Object must NOT be null" ); + } + + + /** + * Assert that two objects( <code>obj1</code> and <code>obj2</code> ) is equal. + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if two objects is not equal + * + * @param obj1 first object to compare + * @param obj2 second object to compare + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + isEqual( + final Object obj1, + final Object obj2, + final String message + ) + { + if ( ObjectUtil.equals( obj1, obj2 ) ) + { + return ; + } + + fail( message ); + } + + + /** + * Assert that two objects( <code>obj1</code> and <code>obj2</code> ) is equal. + * + * Throw {@link IllegalArgumentException} with "Objects are not equal" message + * + * if two objects is not equal + * + * @param obj1 first object to compare + * @param obj2 second object to compare + * + * @see #isEqual(Object, Object, String) + */ + public static + void + isEqual( + final Object obj1, + final Object obj2 + ) + { + isEqual( obj1, obj2, "Objects are not equal" ); + } + + /** + * Assert that <code>text</code> has any readible character + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>text</code> is <code>null</code> or empty string. + * + * @param text string to check + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + hasLength( + final String text, + final String msg + ) + { + if( StringUtil.hasLength( text ) ) + { + return ; + } + fail( msg ); + } + /** + * Assert that <code>text</code> has any readible character + * + * Throw {@link IllegalArgumentException} with "String argument must have length; it must not be null or empty" message + * + * if <code>text</code> is <code>null</code> or empty string. + * + * @param text string to check + * + * @see #hasLength(String, String) + */ + public static + void + hasLength( + final String text + ) + { + hasLength( text, "String argument must have length; it must not be null or empty" ); + } + + + /** + * Assert that <code>text</code> has any readible character + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>text</code> is <code>null</code>, empty string or string containing only unvisible character + * + * @param text string to check + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + hasText( + final String text, + final String message + ) + { + if ( StringUtil.hasText( text ) ) + { + return ; + } + fail( message ); + } + + /** + * Assert that <code>text</code> has any readible character + * + * Throw {@link IllegalArgumentException} with "String argument must have text; it must not be null, empty, or blank" message + * + * if <code>text</code> is <code>null</code>, empty string or string containing only unvisible character + * + * @param text string to check + * + * @see #hasText(String, String) + */ + public static + void + hasText( + final String text + ) + { + hasText( text, "String argument must have text; it must not be null, empty, or blank" ); + } + + /** + * Assert that <code>textToSearch</code> does not have <code>substring</code> in part. + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if assertion is failure. + * + * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>. + * + * @param textToSearch search target string + * @param substring keyword to search + * @param msg exception's message to throw + * + * @see String#contains(CharSequence) + */ + public static + void + doesNotContain( + final String textToSearch, + final String substring, + final String msg + ) + { + if ( !StringUtil.hasLength( textToSearch ) ) + { + return ; + } + + if ( !StringUtil.hasLength( substring ) ) + { + return ; + } + + if ( !textToSearch.contains( substring ) ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>textToSearch</code> does not have <code>substring</code> in part. + * + * Throw {@link IllegalArgumentException} with "String argument must not contain the substring [<code>substring</code>]" message + * + * if assertion is failure. + * + * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>. + * + * @param textToSearch search target string + * @param substring keyword to search + * + * @see #doesNotContain(String, String, String) + */ + public static + void + doesNotContain( + final String textToSearch, + final String substring + ) + { + doesNotContain( + textToSearch, + substring, + "String argument must not contain the substring [" + substring + "]" + ); + } + + /** + * Assert that <code>textToSearch</code> has <code>substring</code> in part. + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if assertion is failure. + * + * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>. + * + * @param textToSearch search target string + * @param substring keyword to search + * @param msg exception's message to throw + * + * @see String#contains(CharSequence) + */ + public static + void + contains( + final String textToSearch, + final String substring, + final String msg + ) + { + if ( !StringUtil.hasLength( textToSearch ) ) + { + return ; + } + if ( !StringUtil.hasLength( substring ) ) + { + return ; + } + if ( textToSearch.contains( substring ) ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>textToSearch</code> does not have <code>substring</code> in part. + * + * Throw {@link IllegalArgumentException} with "String argument must contain the substring [<code>substring</code>]" message + * + * if assertion is failure. + * + * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>. + * + * @param textToSearch search target string + * @param substring keyword to search + * + * @see #doesContain(String, String, String) + */ + public static + void + contains( + final String textToSearch, + final String substring + ) + { + contains( + textToSearch, + substring, + "String argument must contain the substring [" + substring + "]" + ); + } + + /** + * Assert that <code>array</code> has a element at least. + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>array</code> is null or empty array. + * + * @param <T> type of array elemtent + * @param array array object to check + * @param msg exception's message to throw + * + * @see ArrayUtil#isEmpty( Object[] ) + */ + public static <T> + void + notEmpty( + final T[] array, + final String message + ) + { + if( ArrayUtil.isEmpty( array ) ) + { + fail( message ); + } + } + + /** + * Assert that <code>array</code> has a element at least. + * + * Throw {@link IllegalArgumentException} with "Array must not be empty: it must contain at least 1 element" message + * + * if <code>array</code> is null or empty array. + * + * @param <T> type of array elemtent + * @param array array object to check + * @param msg exception's message to throw + * + * @see #notEmpty( Object[] ) + */ + public static + void + notEmpty( + final Object[] array + ) + { + notEmpty( array, "Array must not be empty: it must contain at least 1 element" ); + } + + /** + * Assert that there is no <code>null</code> in array elements + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>array</code> has null element. + * + * @param array array to check + * @param msg exception's message to throw + * + * @see #fail(Object) + */ + public static + void + noNullElements( + final Object[] array, + final String msg + ) + { + + for ( int i=0, n=ArrayUtil.size( array ) ; i<n ; ++i ) + { + if ( null != array[i] ) + { + continue; + } + + fail( msg ); + } + } + + /** + * Assert that there is no <code>null</code> in array elements + * + * Throw {@link IllegalArgumentException} with "Array must not contain any null elements" message + * + * if <code>array</code> has null element. + * + * @param array array to check + * + * @see #noNullElements(Object[], String) + */ + public static + void + noNullElements( + final Object[] array + ) { + noNullElements( array, "Array must not contain any null elements" ); + } + + + /** + * Assert that <code>collection</code>is not empty + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>collection</code> has no element + * + * @param collection {@link Collection} to check + * @param msg exception's message to throw + * + * @see CollectionUtil#isEmpty( Collection ) + * @see #fail(Object) + */ + public static + void + notEmpty( + final Collection<?> collection, + final String msg + ) + { + if( !CollectionUtil.isEmpty( collection ) ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>collection</code>is not empty + * + * Throw {@link IllegalArgumentException} with "Collection must not be empty: it must contain at least 1 element" message + * + * if <code>collection</code> has no element + * + * @param collection {@link Collection} to check + * + * @see #notEmpty(Collection, String) + */ + public static + void + notEmpty( + final Collection<?> collection + ) + { + notEmpty( collection, "Collection must not be empty: it must contain at least 1 element" ); + } + + /** + * Assert that <code>map</code>is not empty + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>map</code> has no element + * + * @param map {@link Map} to check + * @param msg exception's message to throw + * + * @see MapUtil#isEmpty( Map ) + * @see #fail(Object) + */ + public static + void + notEmpty( + final Map<?, ?> map, + final String msg + ) + { + if ( !MapUtil.isEmpty( map ) ) + { + return ; + } + fail( msg ); + } + + /** + * Assert that <code>map</code>is not empty + * + * Throw {@link IllegalArgumentException} with "Map must not be empty; it must contain at least one entry" message + * + * if <code>map</code> has no element + * + * @param map {@link Map} to check + * + * @see #notEmpty(Map, String) + */ + public static + void + notEmpty( + final Map<?, ?> map + ) + { + notEmpty( map, "Map must not be empty; it must contain at least one entry" ); + } + + /** + * Assert that <code>obj</code> is instance of <code>type</code> + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>obj</code> is <code>null</code> or not instance of <code>type</code> + * + * @param type {@link Class} to check + * @param obj instance object to check + * @param msg exception's message to throw + * + * @see Class#isInstance(Object) + * @see #fail(Object) + */ + public static + void + isInstanceOf( + final Class<?> type, + final Object obj, + final String msg + ) + { + notNull( type, "Type to check against must not be null" ); + if( type.isInstance( obj ) ) + { + return ; + } + + fail( MessageFormat.format( + "{0}, Object of class [{1}] must be aan instance of {2}", + msg, + (( null == obj ) ?"null":obj.getClass().getName()), + type + ) ); + } + + /** + * Assert that <code>obj</code> is instance of <code>type</code> + * + * Throw {@link IllegalArgumentException} + * + * if <code>obj</code> is <code>null</code> or not instance of <code>type</code> + * + * @param type {@link Class} to check + * @param obj instance object to check + * + * @see #isInstanceOf(Class, Object, String) + */ + public static + void + isInstanceOf( + final Class<?> type, + final Object obj + ) + { + isInstanceOf( type, obj, "" ); + } + + /** + * Assert that <code>superType</code> is assignable type from <code>subType</code> instance + * + * Throw {@link IllegalArgumentException} with <code>msg</code> message + * + * if <code>superType</code> or <code>subType</code> is <code>null</code> or if assertion is failure + * + * @param superType super type candidate + * @param subType subtype candidate + * @param msg exception's message to throw + * + * @see Class#isAssignableFrom(Class) + * @see #fail(Object) + */ + public static + void + isAssignable( + final Class<?> superType, + final Class<?> subType, + final String msg + ) + { + notNull( superType, "Type to check against must not be null" ); + notNull( subType, "Type to assign must not be null" ); + if( superType.isAssignableFrom( subType ) ) + { + return ; + } + fail( MessageFormat.format( + "{0}, {1} is not assignable to {2}", + msg, + subType, + superType + ) ); + } + + /** + * Assert that <code>superType</code> is assignable type from <code>subType</code> instance + * + * Throw {@link IllegalArgumentException} + * + * if <code>superType</code> or <code>subType</code> is <code>null</code> or if assertion is failure + * + * @param superType super type candidate + * @param subType subtype candidate + * + * @see #isAssignable(Class, Class, String) + */ + public static + void + isAssignable( + final Class<?> superType, + final Class<?> subType + ) + { + isAssignable( superType, subType, "" ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java b/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java index 87c370476..96111daa3 100644 --- a/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java +++ b/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java @@ -25,6 +25,8 @@ package org.tizen.common.util; +import static org.tizen.common.util.SWTUtil.asyncExec; + import java.io.File; import org.eclipse.swt.SWT; @@ -52,8 +54,7 @@ public class BrowserWrapper { } public void setInput(final File f) { - browser.getDisplay().asyncExec(new Runnable() { - @Override + asyncExec(new Runnable() { public void run() { if (!browser.isDisposed()) { browser.setUrl(f.getAbsolutePath()); diff --git a/org.tizen.common/src/org/tizen/common/util/CipherUtil.java b/org.tizen.common/src/org/tizen/common/util/CipherUtil.java new file mode 100644 index 000000000..6bf9a91eb --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/CipherUtil.java @@ -0,0 +1,97 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESedeKeySpec; + +import org.tizen.common.util.log.Logger; + +import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; + +/** + * CipherUtil + * + * This is a util class for encrypting and decrypting plain texts. + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + */ +public class CipherUtil { + + private static final String password = "KYANINYLhijklmnopqrstuvwx"; + private static SecretKey SECRETE_KEY; + private static Cipher DES_CIPHER; + private static final String ALGORITHM = "DESede"; + + static { + try { + byte key[] = password.getBytes(); + DESedeKeySpec desKeySpec = new DESedeKeySpec(key); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); + SECRETE_KEY = keyFactory.generateSecret(desKeySpec); + + DES_CIPHER = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding"); + } catch (Throwable t) { + Logger.error("Exception occurred while creating secret key", t); + } + } + + private static byte[] decryptByDES(byte[] bytes) throws Exception{ + DES_CIPHER.init(Cipher.DECRYPT_MODE, SECRETE_KEY); + + return DES_CIPHER.doFinal(bytes); + } + + private static byte[] encryptByDES(String s) throws Exception { + DES_CIPHER.init(Cipher.ENCRYPT_MODE, SECRETE_KEY); + + return DES_CIPHER.doFinal(s.getBytes()); + } + + /** + * Decrypt cipher message + * + * @param s cipher message which will be decrypted. + * @return decrypted plain text. + * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core) + */ + public static String getDecryptedString(String s) throws Exception { + return new String(decryptByDES(Base64.decode(s))); + } + + /** + * Encrypt plain text + * + * @param s plain text which will be encrypted. + * @return encrypted cipher text. + * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core) + */ + public static String getEncryptedString(String s) throws Exception { + return new String(Base64.encode(encryptByDES(s))); + } +}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/util/CollectionMap.java b/org.tizen.common/src/org/tizen/common/util/CollectionMap.java new file mode 100644 index 000000000..903757962 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/CollectionMap.java @@ -0,0 +1,232 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; + + +/** + * CollectionUtil. + * + * Helper related to collection( Set, List, etc ) + * + * Characters for both {@link Collection} and {@link Map} + * + * You can add and remove not only key-value pair but also a set of key-value + * + * Replace key-value set to <code>null</code> if no values + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @param <K> key type + * @param <V> value type + */ +public class +CollectionMap<K, V> +{ + + /** + * Map to manage key-values + */ + protected final HashMap<K, Collection<V>> map = new LinkedHashMap<K, Collection<V>>(); + + + /** + * Create values container + * + * Determine a method for management of values + * + * Modify this method if you want to change value container + * + * @return value containing {@link Collection} + */ + protected + Collection<V> + createValues() + { + return new ArrayList<V>(); + } + + /** + * Add key-value pair + * + * @param key key to add + * @param value value to add + */ + public + void + put( + final K key, + final V value + ) + { + Collection<V> values = map.get( key ); + if ( null == values ) + { + values = createValues(); + map.put( key, values ); + } + + values.add( value ); + } + + /** + * Return keys + * + * @return {@link Collection} for key + * + * @see java.util.Map#keySet() + */ + public + Collection<K> + keySet() { + return map.keySet(); + } + + /** + * Return values for <code>key</code> + * + * Return <code>null</code> if no values + * + * @param key key for values + * + * @return key related values + */ + public + Collection<V> + get( + final K key + ) + { + return map.get( key ); + } + + /** + * Replace a set of key-values + * + * @param key key for key-valeus + * @param values values for key-values + * + * @return old values for <code>key</code> + */ + public + Collection<V> + set( + final K key, + final Collection<V> values + ) + { + return map.put( key, values ); + } + + /** + * Remove a set of key-values + * + * @param key key for key-values + * + * @return values to be removed + */ + public + Collection<V> + remove( + final K key + ) + { + return map.remove( key ); + } + + /** + * Remove key-value pair from a set and return values after change + * + * Return <code>null</code> if no values + * + * @param key key for key-value + * @param value value for key-value + * + * @return values after change + */ + public + Collection<V> + remove( + final K key, + final V value + ) + { + final Collection<V> values = map.get( key ); + values.remove( value ); + + if ( values.isEmpty() ) + { + map.remove( key ); + return null; + } + + return values; + } + + /** + * Remove all sets + */ + public + void + clear() + { + map.clear(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + final StringBuilder buffer = new StringBuilder(); + + buffer.append( "CollectionMap[" ); + + boolean bInit = false; + + for ( final K key : map.keySet() ) + { + if ( bInit ) + { + buffer.append( ", " ); + } + bInit = true; + buffer.append( key ); + buffer.append( '=' ); + buffer.append( map.get( key ) ); + } + + buffer.append( "]" ); + + return buffer.toString(); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java b/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java new file mode 100644 index 000000000..2d5a024f4 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java @@ -0,0 +1,1890 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import static org.tizen.common.util.StringUtil.EMPTY_STRING; +import static org.tizen.common.util.StringUtil.NULL_STRING; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.tizen.common.util.ArrayUtil.ArrayIterator; + +/** + * CollectionUtil. + * + * Helper related to collection( Set, List, etc ) + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class CollectionUtil +{ + + /** + * Empty bytes + */ + protected static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; + protected static final byte[] EMPTY_BYTES = EMPTY_BYTE_ARRAY; + + private static final String ARRAY_START = "{"; + + private static final String ARRAY_END = "}"; + + private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; + + private static final String ARRAY_ELEMENT_SEPARATOR = ", "; + + private static final Set<Class<?>> APPROXIMABLE_COLLECTION_TYPES = + Collections.unmodifiableSet( new HashSet<Class<?>>( Arrays.asList( new Class<?>[] { + Collection.class, + Set.class, HashSet.class, SortedSet.class, LinkedHashSet.class, TreeSet.class, + List.class, LinkedList.class, ArrayList.class + } ) ) ); + + private static final Set<Class<?>> APPROXIMABLE_MAP_TYPES = + Collections.unmodifiableSet( new HashSet<Class<?>>( Arrays.asList( new Class<?>[] { + Map.class, SortedMap.class, HashMap.class, LinkedHashMap.class, TreeMap.class + } ) ) ); + + + + /* Object */ + /** + * Empty Collection + */ + public static final Collection<Object> EMPTY_COLLECTION = + Collections.unmodifiableCollection( new ArrayList<Object>() ); + + /** + * protected constructor + */ + protected CollectionUtil() {} + + /** + * <p> + * check <code>collection</code> has no element. + * + * use without null check. + * + * Old style + * + * <code> + * List list = null; + * ... + * if ( null != list && !list.isEmpty() ) { + * ... + * } + * </code> + * + * Usage : + * <p> + * + * <code> + * List list = null; + * ... + * if ( !CollectionUtil.isEmpty( list ) ) { + * ... + * } + * </code> + * + * or "import static" style if you use JDK6 + * + * </code> + * import static org.tizen.common.util.CollectionUtil.isEmpty; + * + * ... + * List list = null; + * ... + * if ( !isEmpty( list ) ) { + * ... + * } + * </code> + * + * @param collection {@link Collection} to check + * + * @return value if collection is empty + */ + public static + boolean + isEmpty( + final Collection<?> collection + ) + { + if ( null == collection ) + { + return true; + } + + return collection.isEmpty(); + } + + /** + * <p> + * Return <code>collection</code>'s size. + * + * use without null check. + * + * Return <code>0</code> if <code>collection</code> is <code>null</code> + * + * <p> + * + * Old style + * <code> + * if ( null != list ) { + * for ( int i = 0, n = list.size() ; i < n ; ++i ) { + * ... + * } + * } + * </code> + * + * + * <code> + * for ( int i = 0, n = CollectionUtil.size( list ) ; i < n ; ++i ) { + * ... + * } + * + * </code> + * or "import static" style if you use JDK6 + * + * </code> + * import static org.tizen.common.util.CollectionUtil.isEmpty; + * ... + * + * for ( int i = 0, n = size( list ) ; i < n ; ++i ) { + * ... + * } + * + * </code> + * + * @param collection {@link Collection} to check + * + * @return size of <code>collection</code> + * + * @see Collection#size() + */ + public static + int + size( + final Collection<?> collection + ) + { + if ( null == collection ) + { + return 0; + } + + return collection.size(); + } + + /** + * <p> + * run <code>runner</code> iterateing element of <code>collection</code>. + * + * use without null-check for <code>collection</code> + * + * delegate error handling to <code>runner</code> + * </p> + * + * <code> + * + * CollectionUtil.iterate( + * new ArrayList<String>( Arrays.asList( "hello", "Hello", "World", null, "Test" ) ), + * new IteratingRunner<String>() { + * public void run( String arg ) { + * ... + * } + * } + * ); + * + * </code> + * + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} containing element + * @param runner {@link Runnable} to execute + * + * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception + * + * @see {@link #iterate(Collection, IteratingRunner, boolean)} + * @see FilterIterator + */ + public static <T> + void + iterate( + final Collection<? extends T> collection, + final IteratingRunner<T> runner + ) + throws InvocationTargetException + { + iterate( collection, runner, false ); + } + + /** + * <p> + * run <code>runner</code> iterateing element of <code>collection</code>. + * + * use without null-check for <code>collection</code> + * + * delegate error handling to <code>runner</code> + * + * </p> + * <code> + * + * CollectionUtil.iterate( + * new ArrayList<String>( Arrays.asList( "hello", "Hello", "World", null, "Test" ) ), + * new IteratingRunner<String>() { + * public void run( String arg ) { + * ... + * } + * }, + * true + * ); + * + * </code> + * + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} containing element + * @param runner {@link Runnable} to execute + * @param bForceProcess flag to iterate continuously when exception occurs + * + * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception + * + * @see FilterIterator + */ + public static <T> + void + iterate( + final Collection<? extends T> collection, + final IteratingRunner<T> runner, + final boolean bForceProcess + ) + throws InvocationTargetException + { + if ( null == runner ) + { + return ; + } + if ( isEmpty( collection ) ) + { + return ; + } + + for ( final T arg : collection ) + { + if ( null == arg && !bForceProcess ) + { + continue ; + } + try + { + runner.run( arg ); + } catch ( Throwable e ) + { + if ( !bForceProcess ) + { + throw new InvocationTargetException( e ); + } + } + } + } + + /** + * <p> + * fiter <code>collection</code> to <code>result</code> using <code>runner</code> + * + * determined if stop or keep going using <code>bForceProcess</code> in case of exception. + * </p> + * + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} to filter + * @param results collection to save result + * @param runner object to determine if filter + * @param bForceProcess flag to keep going when exception occurs + * + * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception + */ + public static <T> + void + filter( + final Collection<? extends T> collection, + final Collection<T> results, + final IteratingAcceptor<T> runner, + final boolean bForceProcess + ) throws InvocationTargetException + { + if ( null == results ) + { + return ; + } + if ( isEmpty( collection ) ) + { + return ; + } + + for ( final T arg : collection ) + { + if ( null == arg && !bForceProcess ) + { + continue ; + } + try + { + if ( runner.accept( arg ) ) + { + results.add( arg ); + } + } catch ( Throwable e ) + { + if ( !bForceProcess ) + { + throw new InvocationTargetException( e ); + } + } + + } + } + + /** + * <p> + * Return first element in <code>collection</code><br> + * + * Return <code>null</code> if <code>collection</code> is null or empty + * </p> + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} to check + * + * @return first elemtn in <code>collection</code> + */ + public static <T> + T + pickupFirst( final Collection<T> collection ) + { + if ( isEmpty( collection ) ) + { + return null; + } + + final Iterator<T> iter = collection.iterator(); + return (iter.hasNext())?(iter.next()):null; + } + + /** + * <p> + * Extract and return first element in <code>collection</code><br> + * + * Return <code>null</code> if <code>collection</code> is null or empty + * </p> + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} to check + * + * @return first elemtn in <code>collection</code> + */ + public static <T> + T + removeFirst( final Collection<T> collection ) + { + if ( isEmpty( collection ) ) + { + return null; + } + + final Iterator<T> iter = collection.iterator(); + if ( iter.hasNext() ) + { + T ret = iter.next(); + iter.remove(); + return ret; + } + return null; + } + + + /** + * <p> + * Return last element in <code>collection</code><br> + * + * Return <code>null</code> if <code>collection</code> is null or empty + * + * Don't use this in case of big data or looping algorithm + * </p> + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} to check + * + * @return last elemtn in <code>collection</code> + */ + public static <T> + T + pickupLast( final Collection<T> collection ) + { + if ( isEmpty( collection ) ) + { + return null; + } + + final Iterator<T> iter = collection.iterator(); + + T temp = null; + while ( iter.hasNext() ) + { + temp = iter.next(); + } + return temp; + } + + /** + * <p> + * Extract and return last element in <code>collection</code><br> + * + * Return <code>null</code> if <code>collection</code> is null or empty + * + * Don't use this in case of big data or looping algorithm + * </p> + * @param <T> type of element in <code>collection</code> + * @param collection {@link Collection} to check + * + * @return last elemtn in <code>collection</code> + */ + public static <T> + T + removeLast( final Collection<T> collection ) + { + if ( isEmpty( collection ) ) + { + return null; + } + + final Iterator<T> iter = collection.iterator(); + + T temp = null; + while ( iter.hasNext() ) + { + temp = iter.next(); + } + iter.remove(); + return temp; + } + + /** + * Convert {@link Enumeration} to {@link Iterator} using decoration pattern + * + * @param <K> element type to be handled by enumertaion + */ + static class + EnumerationAdapter<K> + implements Iterator<K> + { + protected final Enumeration<K> enumeration; + /** + * Constructor with {@link Enumeration} + * + * @param enumeration {@link Enumeration} to convert + */ + public + EnumerationAdapter( + final Enumeration<K> enumeration + ) + { + if ( null == enumeration ) + { // Fast fail + throw new NullPointerException(); + } + + this.enumeration = enumeration; + } + + /* (non-Javadoc) + * @see java.util.Iterator#hasNext() + */ + @Override + public + boolean + hasNext() + { + return enumeration.hasMoreElements(); + } + + /* (non-Javadoc) + * @see java.util.Iterator#next() + */ + @Override + public + K + next() + { + return enumeration.nextElement(); + } + + /* (non-Javadoc) + * @see java.util.Iterator#remove() + */ + @Override + public + void + remove() + { + throw new UnsupportedOperationException(); + } + } + + /** + * + * Return Iterator to be converted from <code>enumeration</code> + * + * @param <E> element type interating <code>enumeration</code> + * @param enumeration {@link Enumeration} object to be converted + * + * @return converted {@link Iterator} + */ + public + static <E> + Iterator<E> + iterator( + final Enumeration<E> enumeration + ) { + return new EnumerationAdapter<E>( enumeration ); + } + + + /** + * Convert array object to {@link List} + * + * @param source array candidate object + * + * @return converted {@link List} + */ + public static + List<?> + asList( + final Object source + ) + { + return Arrays.asList( ArrayUtil.toObjectArray( source ) ); + } + + /** + * + * Add array object to <code>collection</code> + * + * @param array array candidate object to be added + * @param collection {@link Collection} to add + * + * @see ArrayUtil#toObjectArray(Object) + */ + public static + void + mergeArrayIntoCollection( + final Object array, + final Collection<Object> collection + ) + { + if ( null == collection ) + { + throw new NullPointerException(); + } + + final Object[] arr = ArrayUtil.toObjectArray( array ); + for ( int i=0, n=arr.length ; i<n ; ++i ) + { + collection.add( arr[i] ); + } + } + + /** + * Check if <code>iterator</code> meet <code>element</code> in iteration + * + * @param iterator iterating object + * @param element object to check + * + * @return <code>true</code> if <code>iterator</code> meet <code>element</code> + */ + public static + boolean + contains( + final Iterator<Object> iterator, + final Object element + ) + { + if ( null == iterator ) + { + return false; + } + + while ( iterator.hasNext() ) + { + final Object candidate = iterator.next(); + if ( ObjectUtil.equals( candidate, element ) ) + { + return true; + } + } + return false; + } + + /** + * Check if <code>enumeration</code> meet <code>element</code> in iteration + * + * @param enumeration iterating object + * @param element object to check + * + * @return <code>true</code> if <code>enumeration</code> meet <code>element</code> + */ + public static + boolean + contains( + final Enumeration<Object> enumeration, + final Object element + ) + { + if ( null == enumeration ) + { + return false; + } + while( enumeration.hasMoreElements() ) + { + final Object candidate = enumeration.nextElement(); + if ( ObjectUtil.equals( candidate, element ) ) + { + return true; + } + } + return false; + } + + + + /** + * Check if <code>collection</code> contains <code>element</code> + * + * @param collection {@link Collection} to check + * @param element object to check + * + * @return <code>true</code> if <code>collection</code> contain <code>element</code> + */ + public static + boolean + contains( + final Collection<Object> collection, + final Object element + ) + { + if ( null == collection ) + { + return false; + } + for ( final Object candidate : collection ) + { + if ( ObjectUtil.equals( candidate, element ) ) + { + return true; + } + } + return false; + } + + /** + * Check and return if <code>source</code> contain any element of <code>candidates</code> + * + * @param source {@link Collection} to check + * @param candidates {@link Collection} whose element is expected in <code>source</code> + * + * @return <code>true</code> if <code>source</code> contain any elemnt of <code>candidates</code> + */ + public static + boolean + containsAny( + final Collection<?> source, + final Collection<?> candidates + ) + { + if ( isEmpty( source ) || isEmpty( candidates) ) + { + return false; + } + + for ( final Object candidate : candidates ) + { + if ( source.contains( candidate ) ) + { + return true; + } + } + return false; + } + + /** + * Check <code>collectionType</code> is approximable collection type + * + * @param collectionType type to check + * + * @return <code>true</code> if <code>collectionType</code> is in {@link #APPROXIMABLE_COLLECTION_TYPES} + * + * @see #APPROXIMABLE_COLLECTION_TYPES + */ + public static + boolean + isApproximableCollectionType( + final Class<?> collectionType + ) + { + return APPROXIMABLE_COLLECTION_TYPES.contains( collectionType ); + } + + /** + * Check <code>mapType</code> is approximable map type + * + * @param mapType type to check + * + * @return <code>true</code> if <code>mapType</code> is in {@link #APPROXIMABLE_MAP_TYPES} + * + * @see #APPROXIMABLE_MAP_TYPES + */ + public static + boolean + isApproximableMapType( + final Class<?> mapType + ) + { + return APPROXIMABLE_MAP_TYPES.contains( mapType ); + } + + /** + * Create <code>collection</code> matched approximable collection + * + * @param <K> containing type + * @param collection {@link Collection} to convert + * @param initialCapacity initial size of created collection + * + * @return created approximable collection + */ + public static <K> + Collection<K> + createApproximableCollection( + final Collection<K> collection, + final int initialCapacity + ) + { + if ( collection instanceof LinkedList<?> ) + { + return new LinkedList<K>(); + } + else if ( collection instanceof List<?> ) + { + return new ArrayList<K>( initialCapacity); + } + else if ( collection instanceof SortedSet<?> ) + { + return new TreeSet<K>( ( (SortedSet<K>)collection).comparator() ); + } + else + { + return new LinkedHashSet<K>( initialCapacity); + } + } + + /** + * @param <K> Map's Key type + * @param <V> Map's Value type + * @param map Map argument + * @param initialCapacity initial argument for Map which will be created + * + * @return created ApproximableMap + */ + public static <K, V> + Map<K, V> + createApproximableMap( + final Map<K, V> map, + final int initialCapacity + ) + { + if ( map instanceof SortedMap<?, ?> ) + { + return new TreeMap<K, V>( ( (SortedMap<K, V>) map).comparator() ); + } + else + { + return new LinkedHashMap<K, V>( initialCapacity ); + } + } + + /* print */ + + /** + * Converts <code>obj</code> object to String. + * + * @param obj object to convert + * + * @return converted String + */ + public static + String + toString( + final Object obj + ) + { + if ( null == obj ) + { + return NULL_STRING; + } + + if ( obj instanceof String ) + { + return (String) obj; + } + else if ( obj instanceof Object[] ) + { + return toString( ( Object[] ) obj ); + } + else if ( obj instanceof boolean[] ) + { + return toString( ( boolean[] ) obj ); + } + else if ( obj instanceof byte[] ) + { + return toString( ( byte[] )obj ); + } + else if ( obj instanceof char[] ) + { + return toString( ( char[] ) obj ); + } + else if ( obj instanceof double[] ) + { + return toString( ( double[] ) obj ); + } + else if ( obj instanceof float[] ) + { + return toString( (float[] ) obj ); + } + else if ( obj instanceof int[] ) + { + return toString( (int[] ) obj ); + } + else if ( obj instanceof long[] ) + { + return toString( ( long[] ) obj ); + } + else if ( obj instanceof short[] ) + { + return toString( ( short[] )obj ); + } + return ObjectUtil.nvl( obj.toString(), EMPTY_STRING ); + } + + /** + * Converts <code>array</code> boolean[] to String. + * + * @param array boolean[] to convert + * + * @return converted String + */ + public static + String + toString( + final boolean[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer= new StringBuilder(); + + buffer.append( ARRAY_START); + for ( int i=0 ; i<length ; ++i ) + { + if ( 0 != i ) { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( toString( array[i] ) ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> byte[] to String. + * + * @param array byte[] to convert + * + * @return converted String + */ + public static + String + toString( + final byte[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer= new StringBuilder(); + + buffer.append( ARRAY_START); + for ( int i=0 ; i<length ; ++i ) + { + if ( 0 != i ) { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( toString( array[i] ) ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> char[] to String. + * + * @param array char[] to convert + * + * @return converted String + */ + public static + String + toString( + final char[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer= new StringBuilder(); + + buffer.append( ARRAY_START); + for ( int i=0 ; i<length ; ++i ) + { + if ( 0 != i ) + { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( toString( array[i] ) ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + + /** + * Converts <code>array</code> short[] to String. + * + * @param array short[] to convert + * + * @return converted String + */ + public static + String + toString( + final short[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer = new StringBuilder(); + for( int i=0 ; i<length ; ++i ) + { + if ( 0 == i ) + { + buffer.append( ARRAY_START ); + } + else + { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( array[i] ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> int[] to String. + * + * @param array int[] to String + * + * @return converted String + */ + public static + String + toString( + final int[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer = new StringBuilder(); + for( int i=0 ; i<length ; ++i ) + { + if ( 0 == i ) + { + buffer.append( ARRAY_START ); + } + else + { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( array[i] ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> long[] to String. + * + * @param array long[] to convert + * + * @return converted String + */ + public static + String + toString( + final long[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer = new StringBuilder(); + for( int i=0 ; i<length ; ++i) + { + if ( 0 == i ) + { + buffer.append( ARRAY_START ); + } + else + { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( array[i] ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> double[] to String. + * + * @param array double[] to convert + * + * @return converted String + */ + public static + String + toString( + final double[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + int length= array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + StringBuilder buffer = new StringBuilder(); + for( int i=0 ; i<length ; ++i ) + { + if ( 0 == i ) + { + buffer.append( ARRAY_START); + } + else + { + buffer.append( ARRAY_ELEMENT_SEPARATOR); + } + + buffer.append( array[i] ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> float[] to String. + * + * @param array float[] to convert + * + * @return converted String + */ + public static + String + toString( + final float[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer = new StringBuilder(); + for( int i=0 ; i < length ; ++i ) + { + if ( 0 == i ) + { + buffer.append( ARRAY_START ); + } + else + { + buffer.append( ARRAY_ELEMENT_SEPARATOR ); + } + + buffer.append( array[i] ); + } + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Converts <code>array</code> Object[] to String. + * + * @param array Object[] to convert + * + * @return converted String + */ + public static <T> + String + toString( + final T[] array + ) + { + if ( null == array ) + { + return NULL_STRING; + } + + final int length = array.length; + + if ( 0 == length ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer= new StringBuilder(); + + buffer.append( ARRAY_START); + buffer.append( concatenate( array, ARRAY_ELEMENT_SEPARATOR ) ); + buffer.append( ARRAY_END ); + return buffer.toString(); + } + + /** + * Returns a String from <code>array</code> Object[] with String separator. + * + * @param array Object[] to combine + * @param separator the delimiter which is used when Object[] combined + * + * @return combined String + */ + public static <E> + String + concatenate( + final E[] array, + final String separator + ) + { + return concatenate( (null==array)?null:new ArrayIterator<E>( array ), separator ); + } + + /** + * Returns a String from col {@link Collection} with String separator. + * + * @param col {@link Collection} object to combine + * @param separator the delimiter which is used when {@link Collection} object combined + * + * @return combined String + */ + public static <E> + String + concatenate( + final Collection<E> col, + final String separator + ) + { + return concatenate( (null==col)?(null):col.iterator(), separator ); + } + + /** + * Returns a String from {@link Iterator} with String separator. + * + * @param iter {@link Iterator} to combine objects + * @param separator the delimiter which is used when {@link Iterator} combined + * + * @return combined String + */ + public static <E> + String + concatenate( + Iterator<E> iter, + final String separator + ) + { + if ( null == iter ) + { + return NULL_STRING; + } + + if ( !iter.hasNext() ) + { + return EMPTY_ARRAY; + } + + final StringBuilder buffer= new StringBuilder(); + boolean bInit = false; + + while ( iter.hasNext() ) + { + Object obj = iter.next(); + if ( bInit ) + { + buffer.append( separator ); + } + bInit = true; + + buffer.append( toString( obj ) ); + } + return buffer.toString(); + } + + /* Hash */ + private static final int MULTIPLIER= 31; + + private static final int INITIAL_HASH = 7; + + /** + * Creates hash value about object. + * <br> + * In case of array, get hash value using object's hash value in the array. + * + * @param obj object to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final Object obj + ) + { + if ( null == obj ) + { + return 0; + } + if ( obj.getClass().isArray() ) + { + if ( obj instanceof Object[] ) + { + return hashCode( (Object[] )obj ); + } + else if ( obj instanceof boolean[] ) + { + return hashCode( (boolean[] )obj ); + } + else if ( obj instanceof byte[] ) + { + return hashCode( (byte[] )obj); + } + else if ( obj instanceof char[] ) + { + return hashCode( (char[] )obj); + } + else if ( obj instanceof double[] ) + { + return hashCode( (double[] )obj); + } + else if ( obj instanceof float[] ) + { + return hashCode( (float[] )obj); + } + else if ( obj instanceof int[] ) + { + return hashCode( (int[] )obj); + } + else if ( obj instanceof long[] ) + { + return hashCode( (long[] )obj); + } + else if ( obj instanceof short[] ) + { + return hashCode( (short[] )obj); + } + } + + return obj.hashCode(); + } + + /** + * Returns hash value about <code>array</code> Object[]. + * + * @param array Object[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final Object[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> boolean[]. + * + * @param array boolean[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final boolean[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> int[]. + * + * @param array int[] to get hash value + * + * @return hash value + */ + public static int + hashCode( + final byte[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + array[i]; + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> char[]. + * + * @param array char[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final char[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> double[]. + * + * @param array double[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final double[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> float[]. + * + * @param array float[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final float[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> int[]. + * + * @param array int[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final int[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> long[]. + * + * @param array long[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final long[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>array</code> short[]. + * + * @param array short[] to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final short[] array + ) + { + if ( null == array ) + { + return 0; + } + + int hash = INITIAL_HASH; + for( int i=0, arraySize=array.length ; i<arraySize ; ++i ) + { + hash = MULTIPLIER * hash + hashCode( array[i] ); + } + + return hash; + } + + /** + * Returns hash value about <code>bool</code> boolean. + * + * @param bool boolean type parameter to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final boolean bool + ) + { + return bool ? 1231 : 1237; + } + + /** + * Return hash value about <code>dbl</code> double. + * + * @param dbl double type parameter to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final double dbl + ) + { + long bits = Double.doubleToLongBits( dbl ); + return hashCode( bits ); + } + + /** + * Returns hash value about <code>flt</code> float. + * + * @param flt float type parameter to get hash value + * + * @return hash value + */ + public static + int + hashCode( + float flt + ) + { + return Float.floatToIntBits( flt ); + } + + + /** + * Returns hash value about <code>lng</code> long. + * + * @param lng long type parameter to get hash value + * + * @return hash value + */ + public static + int + hashCode( + final long lng + ) + { + return (int) ( lng ^ ( lng >>> 32 ) ); + } + + /* Equals */ + /** + * Returns whether it is same object type or not by comparing each column's type of {@link Collection} object. + * + * @param <K> object type about {@link Collection} + * @param cols {@link Collection} objects + * + * @return true if each column's type of the {@link Collection} object is same + */ + @SuppressWarnings("unchecked") + public static <K> + boolean + equals( + final Collection<? extends K>... cols + ) + { + + // flag if collection is null + boolean bInit = false; + int size = 0; + for ( final Collection<? extends K> col : cols ) + { + if ( !bInit ) + { + if ( null == col ) + { + size = -1; + } + else + { + size = col.size(); + } + bInit = true; + } + if ( size < 0 ) + { + if ( null != col ) + { + return false; + } + } + else if ( null == col || col.size() != size ) + { + return false; + } + } + if ( size < 0 ) + { + return true; + } + + final Iterator<? extends K>[] iters = new Iterator[cols.length]; + for ( int i = 0, n = iters.length ; i<n ; ++i ) + { + iters[i] = cols[i].iterator(); + } + + while ( iters[0].hasNext() ) + { + final K obj = iters[0].next(); + for ( int i = 1, n = iters.length ; i<n ; ++i ) + { + final K other = iters[i].next(); + + if ( !ObjectUtil.equals( obj, other ) ) + { + return false; + } + } + } + + return true; + } + + /** + * Returns whether it is same object type or not by comparing each column's type of Object[]. + * + * @param objsVar target objects + * + * @return true if each column's type of the Object[] is same + * + */ + public static + boolean + equals( + final Object[]... objsVar + ) + { + // flag if collection is null + boolean bInit = false; + int size = 0; + for ( final Object[] objs : objsVar ) + { + if ( !bInit ) + { + if ( null == objs ) + { + size = -1; + } + else + { + size = objs.length; + } + bInit = true; + } + if ( size < 0 ) + { + if ( null != objs ) + { + return false; + } + } + else if ( null == objs || objs.length != size ) + { + return false; + } + } + if ( size < 0 ) + { + return true; + } + + + for ( int i=1, n=objsVar.length ; i<n ; ++i ) + { + for ( int j=0 ; j<size ; ++j ) + { + if ( !ObjectUtil.equals( objsVar[0][j], objsVar[i][j] ) ) + { + return false; + } + } + } + return true; + + } + + /** + * <p> + * Swaps <code><I>i</I></code>th object's location with <code><I>j</I></code>th object in <code>objs</code> Object[]. + * </p> + * @param objs target + * @param i location of object to be swapped + * @param j location of object to be swapped + */ + public static + void + swap( + final Object[] objs, + final int i, + final int j + ) + { + Object temp = objs[i]; + objs[i] = objs[j]; + objs[j] = temp; + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java b/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java index c0cb6f545..8e7ddb603 100644 --- a/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java +++ b/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java @@ -75,8 +75,10 @@ public class ControlFileConfig { public boolean store(){ File folder = new File(this.path).getParentFile(); - if(folder==null||!folder.exists()) + if( !folder.exists() ) + { folder.mkdirs(); + } this.isExist = PropertyUtil.storeProperties(path, props); return this.isExist; diff --git a/org.tizen.common/src/org/tizen/common/util/DialogUtil.java b/org.tizen.common/src/org/tizen/common/util/DialogUtil.java index 3335ba125..8961df713 100644 --- a/org.tizen.common/src/org/tizen/common/util/DialogUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/DialogUtil.java @@ -26,7 +26,6 @@ package org.tizen.common.util; import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; @@ -48,7 +47,7 @@ public abstract class DialogUtil { } public static void openMessageDialog(final Shell shell, final String title, final String message) { - Display.getDefault().syncExec(new Runnable() { + SWTUtil.syncExec(new Runnable() { public void run() { MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); dialog.setText(title); @@ -60,7 +59,7 @@ public abstract class DialogUtil { public static void openProxyDialog(final String text, String message) { final String msg = message; - Display.getDefault().syncExec(new Runnable() { + SWTUtil.syncExec(new Runnable() { public void run() { MessageBox dialog = new MessageBox(new Shell(), SWT.ERROR | SWT.ICON_INFORMATION); dialog.setText(text); @@ -83,7 +82,7 @@ public abstract class DialogUtil { } public static void openErrorDialog(final Shell shell, final String title, final String message) { - Display.getDefault().syncExec(new Runnable() { + SWTUtil.syncExec(new Runnable() { public void run() { MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); dialog.setText(title); @@ -106,7 +105,7 @@ public abstract class DialogUtil { public static int openQuestionDialog(String message) { synchronized (lockQuestion) { final String msg = message; - Display.getDefault().syncExec(new Runnable() { + SWTUtil.syncExec(new Runnable() { public void run() { MessageBox dialog = new MessageBox(new Shell(), SWT.YES | SWT.NO | SWT.ICON_QUESTION); dialog.setMessage(msg); diff --git a/org.tizen.common/src/org/tizen/common/util/EFSUtil.java b/org.tizen.common/src/org/tizen/common/util/EFSUtil.java new file mode 100755 index 000000000..47d33ea06 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/EFSUtil.java @@ -0,0 +1,303 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Jihoon Song <jihoon80.song@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import java.net.URI; + +import org.eclipse.core.filesystem.EFS; +import org.eclipse.core.filesystem.IFileStore; +import org.eclipse.core.filesystem.IFileSystem; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.internal.ide.dialogs.IDEResourceInfoUtils; +import org.eclipse.ui.internal.ide.dialogs.IFileStoreFilter; +import org.tizen.common.Surrogate; +import org.tizen.common.core.application.Messages; + +/** + * EFSUtil. + * + * Helper related to Eclipse File System + * + * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core) + */ +public class EFSUtil { + + public enum DialogChoicer { + YesToAll, + NoToAll, + Yes, + No, + Cancel; + + /** + * Get DialogChoicer's all value + * + * @return String array with DialogChoicer's values + */ + public static String[] toStringArray() { + DialogChoicer[] choicers = DialogChoicer.values(); + String[] values = new String[choicers.length]; + for (DialogChoicer choicer : choicers) { + values[choicer.ordinal()] = choicer.name(); + } + return values; + } + + public static DialogChoicer valueFromOrdinal(int ordinal) { + for (DialogChoicer choicer : values()) { + if (choicer.ordinal() == ordinal) { + return choicer; + } + } + return DialogChoicer.Cancel; + } + } + + private static Surrogate<IFileSystem> fileSystemSurrogate = new Surrogate<IFileSystem>() { + @Override + public IFileSystem getAdapter() { + return EFS.getLocalFileSystem(); + } + }; + + private static final String defaultTask = ""; //$NON-NLS-1$ + private static final int defaultTicks = 100; // TODO : will add automatically calculate method + + private static final IFileStoreFilter defaultFilter = new IFileStoreFilter() { + @Override + public boolean accept(IFileStore store) { + return true; + } + }; + + + // Constructor + private EFSUtil() {} + + public static void setFileSystemSurrogate(Surrogate<IFileSystem> surrogate) { + EFSUtil.fileSystemSurrogate = surrogate; + } + + /** + * Get IFileSystem based on Surrogate<IFileSystem> for this class + * + * @return IFileStoreFilter + */ + protected static IFileSystem getFileSystem() { + return fileSystemSurrogate.getAdapter(); + } + + /** + * Get a default IFileStoreFilter that always returns true + * + * @return IFileStoreFilter + */ + public static IFileStoreFilter getDefaultFileStoreFilter() { + return defaultFilter; + } + + /** + * Detect whether resource exist. + * + * @param fileURI + */ + public static boolean isExistResource(URI fileURI) { + IFileStore fileStore = getFileSystem().getStore(fileURI); + return isExistResource(fileStore); + } + + /** + * Detect whether resource exist. + * + * @param fileStore + */ + public static boolean isExistResource(IFileStore fileStore) { + return (fileStore != null) ? fileStore.fetchInfo().exists() : false; + } + + /** + * Detect whether resource exist. if exist this, open dialog + * + * @param parentShell dialog's parent shell + * @param title dialog title + * @param msg dialog message + * @param previousChoice previous DialogChoicer value + * @param fileStore + * @return in case of previousChoice is Yes or No, return user choice status. any else return previous status + */ + public static DialogChoicer isExistResourceWithDialog(Shell parentShell, + String title, String msg, DialogChoicer previousChoice, IFileStore fileStore) { + + Assert.notNull(parentShell); + Assert.notNull(msg); + Assert.notNull(previousChoice); + Assert.notNull(fileStore); + + switch (previousChoice) { + case Yes : + case No : + break; + case YesToAll : + case NoToAll : + case Cancel : + default : + return previousChoice; + } + + if (isExistResource( fileStore )) { + MessageDialog msgDialog = new MessageDialog(parentShell, + title, null, msg, MessageDialog.NONE, DialogChoicer.toStringArray(), + DialogChoicer.Cancel.ordinal()); + + int msgResult = msgDialog.open(); + + return DialogChoicer.valueFromOrdinal(msgResult); + } + + return DialogChoicer.Yes; + } + + /** + * Copy file or directory using Eclipse File System + * + * @param source the source URI of the copy. If null, NullPointerException occur. + * @param destination the destination URI of the copy. If null, NullPointerException occur. + * @param options bit-wise or of option flag constants ({@link EFS#OVERWRITE} or {@link EFS#SHALLOW}). + * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired + * + * @author Jihoon Song {@literal <jihoon80.song@samsung.com>} (S-Core) + */ + public static void copy(URI source, URI destination, int options, + IProgressMonitor monitor) throws CoreException { + Assert.notNull(source); + Assert.notNull(destination); + + monitor = ObjectUtil.nvl(monitor, new NullProgressMonitor()); + + try { + monitor.beginTask(defaultTask, defaultTicks); + + getFileSystem().getStore(source).copy(getFileSystem().getStore( destination ), options, monitor); + } finally { + monitor.done(); + } + } + + /** + * Copy file or directory using EFS with IFileStoreFilter. + * If file already exist, open selectable message dialog. + * If the user selected Cancel, OperationCanceledException occur + * + * @param source the source URI of the copy. If null, NullPointerException occur. + * @param destination the destination URI of the copy. If null, NullPointerException occur. + * @param fileFilter the child file filter in source, if <code>null</code>, the default file filter is used + * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired + * @throws CoreException + */ + public static DialogChoicer copyWithFilter(URI source, URI destination, IFileStoreFilter fileFilter, + IProgressMonitor monitor) throws CoreException { + return copyWithFilter(source, destination, fileFilter, DialogChoicer.Yes, monitor); + } + + /** + * Copy file or directory using EFS with IFileStoreFilter. + * If file already exist, open selectable message dialog. + * If the user selected Cancel, OperationCanceledException occur + * + * @param source the source URI of the copy. If null, NullPointerException occur. + * @param destination the destination URI of the copy. If null, NullPointerException occur. + * @param fileFilter the child file filter in source, if <code>null</code>, the default file filter is used + * @param previousChoice apply user configuration. if YesToAll or NoToAll, don't ask your choice. + * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired + * @throws CoreException + */ + public static DialogChoicer copyWithFilter(URI source, URI destination, IFileStoreFilter fileFilter, + DialogChoicer previousChoice, IProgressMonitor monitor) throws CoreException { + Assert.notNull(source); + Assert.notNull(destination); + + monitor = ObjectUtil.nvl(monitor, new NullProgressMonitor()); + + try { + monitor.beginTask(defaultTask, defaultTicks); + + // fileFilter must be not null, because IDEResourceInfoUtils don't check null. + if (fileFilter == null) { + fileFilter = getDefaultFileStoreFilter(); + } + + return internalCopyWithFilter(getFileSystem().getStore( source ), + getFileSystem().getStore( destination ), + fileFilter, previousChoice, monitor); + } finally { + monitor.done(); + } + } + + private static DialogChoicer internalCopyWithFilter(IFileStore source, IFileStore destination, + IFileStoreFilter fileFilter, DialogChoicer previousChoice, IProgressMonitor monitor) + throws CoreException { + Assert.notNull(source); + Assert.notNull(destination); + + previousChoice = isExistResourceWithDialog( + ViewUtil.getWorkbenchWindow().getShell(), Messages.FileExistDialogTitle, + Messages.bind( Messages.FileExistMsg, destination.getName() ), + previousChoice, destination); + + switch (previousChoice) { + case YesToAll : + case Yes : + source.copy(destination, EFS.OVERWRITE | EFS.SHALLOW, monitor); + break; + case Cancel : + throw new OperationCanceledException(); + case NoToAll : + case No : + break; + default: + break; + } + monitor.worked(1); + + // traverse child resources + if (source.fetchInfo().isDirectory()) { + IFileStore[] childStores = IDEResourceInfoUtils.listFileStores(source, fileFilter, null); + for (IFileStore childStore : childStores) { + previousChoice = internalCopyWithFilter(childStore, + destination.getChild( childStore.getName() ), + fileFilter, previousChoice, monitor); + } + } + + return previousChoice; + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/FileUtil.java b/org.tizen.common/src/org/tizen/common/util/FileUtil.java index eca82e5b4..59befe244 100644 --- a/org.tizen.common/src/org/tizen/common/util/FileUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/FileUtil.java @@ -1,29 +1,31 @@ /* -* Common -* -* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. -* -* Contact: -* Kangho Kim <kh5325.kim@samsung.com> -* -* 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. -* -* Contributors: -* - S-Core Co., Ltd -* -*/ + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Kangho Kim <kh5325.kim@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ package org.tizen.common.util; +import static org.tizen.common.util.IOUtil.tryClose; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; @@ -36,49 +38,174 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.net.URI; - -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.filesystem.IFileSystem; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; +import org.tizen.common.util.log.Logger; /** * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) */ public class FileUtil { - public static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ - private static final int BUFFER_SIZE = 8192; /** + * Create directory. + * @param dir + * @return If directory couldn't be created, return false. Otherwise, return true. + */ + public static boolean createDirectory(File dir) { + return dir.mkdirs(); + } + + /** + * Create directory. + * @param fullPath + * @return If directory couldn't be created, return false. Otherwise, return true. + */ + public static boolean createDirectory(String fullPath) { + return createDirectory(new File(fullPath)); + } + + /** + * Create directory. + * @param dirName + * @param destDir If destDir is not set(null), then use user's current directory. + * @return If directory couldn't be created, return false. Otherwise, return true. + */ + public static boolean createDirectory(String dirName, String destDir) { + if (dirName == null) + throw new NullPointerException(); + + if (destDir == null) + destDir = System.getProperty("user.dir"); + + String fullPath = FilenameUtil.addTailingPath(destDir, dirName); + + return createDirectory(new File(fullPath)); + } + + /** + * Create text file. + * + * @param file + * @param text Input file's context. + * @param encoding If encoding is not set(null), then use system's default encoding. + * + * @return If file create fail, return false. Otherwise, return true. + * + * @throws IOException If creating file's directory does not exist, it throws IOException + */ + public static boolean createTextFile(File file, String text, String encoding) throws IOException { + if (!file.createNewFile()) + return false; + + return writeTextFile(file, text, encoding); + } + + /** + * Create text file. + * + * @param fullPath + * @param text Input file's context. + * @param encoding If encoding is not set(null), then use system's default encoding. + * + * @return If file create fail, return false. Otherwise, return true. + * + * @throws IOException If creating file's directory does not exist, it throws IOException + */ + public static boolean createTextFile(String fullPath, String text, String encoding) throws IOException { + return createTextFile(new File(fullPath), text, encoding); + } + + /** + * Create text file. + * + * @param fileName + * @param text Input file's context. + * @param destDir If destDir is not set(null), then use user's current directory. + * @param encoding If encoding is not set(null), then use system's default encoding. + * + * @return If file create fail, return false. Otherwise, return true. + * + * @throws IOException If creating file's directory does not exist, it throws IOException + */ + public static boolean createTextFile(String fileName, String text, String destDir, String encoding) throws IOException { + if (fileName == null) + throw new NullPointerException(); + + if (destDir == null) + destDir = System.getProperty("user.dir"); + + String fullPath = FilenameUtil.addTailingPath(destDir, fileName); + + return createTextFile(fullPath, text, encoding); + } + + /** * write text into given file + * + * @param file + * @param text Input context + * @param encoding If encoding is not set(null), then use system's default encoding. + * + * @return If file write success, return true. + * + * @throws IOException If don't write file, it throws IOException */ - public static void writeTextFile(File file, String text, String encoding) throws IOException { - BufferedWriter out = null; - + public static boolean writeTextFile(File file, String text, String encoding) throws IOException { if (encoding == null) { // if encoding is not set then use default encoding encoding = System.getProperty("file.encoding"); } - + + File parent = file.getParentFile(); + if (!parent.exists()) { + if (!parent.mkdirs()) { + throw new IOException("File write error. Cannot create directory - " + parent.getAbsolutePath()); + } + } + + BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding), BUFFER_SIZE); out.write(text.toCharArray(), 0, text.length()); out.flush(); + } catch (IOException e) { + throw e; } finally { if (out != null) { out.close(); } } + + return true; } /** - * read text from given file + * Read text from given file. + * + * @param file + * @param encoding + * + * @return content from file + * + * @throws IOException */ public static String readTextFile(File file, String encoding) throws IOException { + return readTextStream(new FileInputStream(file), encoding); + } + + /** + * Read text from given inputStream. + * + * @param input + * @param encoding + * + * @return content from input + * + * @throws IOException + * + */ + public static String readTextStream(InputStream input, String encoding) throws IOException { StringBuilder text = new StringBuilder(); - char[] buffer = new char[BUFFER_SIZE]; BufferedReader in = null; if (encoding == null) { // if encoding is not set then use default encoding @@ -86,15 +213,10 @@ public class FileUtil { } try { - in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding), BUFFER_SIZE); - int nRead = 0; - while ((nRead = in.read(buffer, 0, buffer.length)) > 0) { - text.append(buffer, 0, nRead); - } + in = new BufferedReader(new InputStreamReader(input, encoding), BUFFER_SIZE); + IOUtil.redirect( in, text ); } finally { - if (in != null) { - in.close(); - } + IOUtil.tryClose( in ); } return text.toString(); @@ -126,7 +248,7 @@ public class FileUtil { } int k = fullName.lastIndexOf("."); - + return (k != -1) ? fullName.substring(0, k) : fullName; } @@ -157,21 +279,6 @@ public class FileUtil { } /** - * copy file or directory using Eclipse File System - * - * @param source The source URI of the copy. - * @param destination The destination URI of the copy. - * @param options bit-wise or of option flag constants ({@link EFS#OVERWRITE} or {@link EFS#SHALLOW}). - * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired - * - * @author Jihoon Song {@literal <jihoon80.song@samsung.com>} (S-Core) - */ - public static void copyUsingEFS(URI source, URI destination, int options, IProgressMonitor monitor) throws CoreException { - IFileSystem fileSystem = EFS.getLocalFileSystem(); - fileSystem.getStore(source).copy(fileSystem.getStore(destination), options, monitor); - } - - /** * redirect input stream to output stream */ public static void redirectStream(InputStream is, OutputStream os) throws IOException { @@ -218,7 +325,8 @@ public class FileUtil { } // makes sure it is not the same file - if (fromFile.getCanonicalPath().equals(toFile.getCanonicalPath())) { + if ( FilenameUtil.equals( fromFile, toFile ) ) + { throw new IOException("Unable to write file " + fromFile + " on itself."); } @@ -229,14 +337,80 @@ public class FileUtil { in = new BufferedInputStream(new FileInputStream(fromFile), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(to, append), BUFFER_SIZE); - byte[] bytes = new byte[BUFFER_SIZE]; - int nRead = 0; - while ((nRead = in.read(bytes, 0, bytes.length)) > 0) { - out.write(bytes, 0, nRead); - } + IOUtil.redirect( in, out ); } finally { - if (in != null) in.close(); - if (out != null) out.close(); + tryClose( in, out ); } } + + /** + * Copy all the files in the source directory to the destination directory. + * If destination directory does not exist, it is created. + * If destination file already exists , it tries to overwrite it. + * + * @param from source directory path + * @param to destination directory path + * @throws IOException + */ + public static void copyRecursively(String from, String to) throws IOException { + File fromDir = new File(from); + File toDir = new File(to); + if (fromDir.exists() == false) { + Logger.error("Directory " + fromDir.getCanonicalPath() + " does not exist."); + return; + } + checkDirectory(fromDir, toDir); + copyRecursivelyWithoutDirChecking(fromDir, toDir); + } + + private static void checkDirectory(File fromDir, File toDir) throws IOException { + if (toDir.exists() == false) { + toDir.mkdirs(); + } else if(toDir.isFile() == true) { + throw new IOException("destination directory " + toDir.toString() + " is a file."); + } + + if (fromDir.exists() == false) { + throw new IOException("source directory " + fromDir.toString() + " does not exist."); + } + + if (fromDir.isFile() == true) { + throw new IOException("source directory " + fromDir.toString() + " is a file."); + } + } + + private static void copyRecursivelyWithoutDirChecking(File fromDir, File toDir) throws IOException { + for(File fromFile: fromDir.listFiles()) { + String newDestPath = toDir.getCanonicalPath(); + if(newDestPath.endsWith(File.separator)) { + newDestPath = newDestPath + fromFile.getName(); + } else { + newDestPath = newDestPath + File.separator + fromFile.getName(); + } + + File toFile = new File(newDestPath); + if(fromFile.isDirectory()) { + copyRecursivelyWithoutDirChecking(fromFile, toFile); + } else if(fromFile.isFile()){ + copyTo(fromFile.getCanonicalPath(), newDestPath); + } + } + } + + /** + * Compares the two files "file1" and "file2". + */ + public static boolean equals(File file1, File file2) throws IOException { + if ( file1 == null || file2 == null) { + return false; + } + String strFile1 = file1.getCanonicalPath(); + String strFile2 = file2.getCanonicalPath(); + + if ( strFile1 == null || strFile2 == null ) { + return false; + } + + return strFile1.equals(strFile2); + } } diff --git a/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java b/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java new file mode 100755 index 000000000..ef4d64843 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java @@ -0,0 +1,422 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import static org.tizen.common.util.ArrayUtil.size; +import static org.tizen.common.util.StringUtil.trimLeadingCharacter; +import static org.tizen.common.util.StringUtil.trimTrailingCharacter; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.regex.Pattern; + +/** + * FilenameUtil. + * + * Helper related to file name + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class FilenameUtil +{ + public static final char SEPARATOR_DIRECTORY = '/'; + public static final int IS_VALID_NAME = 0; + public static final int HAS_INVALID_CHARACTER = 1; + public static final int HAS_NO_NAME = 2; + public static final int IS_NULL = 3; + + /** + * Separate path to directory name fragements + * + * @param path file path + * + * @return canonical path's fragements + */ + public static + String[] + getCanonicalFragments( final String path ) + { + final String safe = path.replace( File.separatorChar, SEPARATOR_DIRECTORY); + final ArrayList<String> ret = new ArrayList<String>(); + for ( final String fragment : safe.split( "" + SEPARATOR_DIRECTORY ) ) + { + if ( StringUtil.isEmpty( fragment ) ) + { + continue; + } + + ret.add( fragment ); + } + return ret.toArray( new String[0] ); + } + + public static + String + getTailingPath( + final String path, + final int start + ) + { + final String[] fragments = getCanonicalFragments( path ); + + final StringBuilder buffer = new StringBuilder(); + + for ( int i = Math.max( 0, size( fragments ) - start ), n = size( fragments ) ; i < n ; ++i ) + { + buffer.append( fragments[i] ); + if ( i < size( fragments ) - 1 ) + { + buffer.append( SEPARATOR_DIRECTORY ); + } + } + + return buffer.toString(); + } + + public static + String + removeTailingPath( + final String path, + final int numberOfPath + ) + { + final String[] fragments = getCanonicalFragments( path ); + + final StringBuilder buffer = new StringBuilder(); + + for ( int i = 0, n = Math.max( 0, size( fragments ) - numberOfPath ) ; i < n ; ++i ) + { + buffer.append( SEPARATOR_DIRECTORY ); + buffer.append( fragments[i] ); + } + + return buffer.toString(); + } + + public static + String + addTailingPath( + final String path, + final String pathToAdd + ) + { + // TODO Verify canonical form + return trimTrailingCharacter( path, SEPARATOR_DIRECTORY ) + SEPARATOR_DIRECTORY + trimLeadingCharacter( pathToAdd, SEPARATOR_DIRECTORY ); + } + + public static + boolean + isAncestor( final String root, final String filePath ) + { + final String[] rootFragments = FilenameUtil.getCanonicalFragments( root ); + final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath ); + + if ( fileFragments.length < rootFragments.length ) + { + return false; + } + + for ( int i = 0, n = rootFragments.length ; i < n ; ++i ) + { + if ( !ObjectUtil.equals( rootFragments[i], fileFragments[i] ) ) + { + return false; + } + } + + + return true; + } + + public static + String + getRelativePath( + final String root, + final String filePath + ) + { + final String[] rootFragments = FilenameUtil.getCanonicalFragments( root ); + final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath ); + + Assert.isTrue( + rootFragments.length < fileFragments.length, + "root must be ancestor[" + root + "] of path[" + filePath + "]" + ); + + for ( int i = 0, n = rootFragments.length ; i < n ; ++i ) + { + Assert.isTrue( ObjectUtil.equals( rootFragments[i], fileFragments[i] ) ); + } + + + + final StringBuilder buffer = new StringBuilder(); + + for ( int i = rootFragments.length, n = fileFragments.length ; i < n ; ++i ) + { + if ( rootFragments.length < i ) + { + buffer.append( SEPARATOR_DIRECTORY ); + } + buffer.append( fileFragments[i] ); + } + + return buffer.toString(); + } + + + /** + * Create canonical form for file path + * + * @param file {@link File} with file path + * + * @return canonical path + * + * @throws IOException If file's path is illegal + */ + public static + String + getCanonicalPath( + final File file + ) + throws IOException + { + final String osCanonicalPath = file.getCanonicalPath(); + + return getCanonicalForm( osCanonicalPath ); + + } + + /** + * Convert path to canonical form + * + * @param path file path + * + * @return canonical path + */ + public static + String + getCanonicalForm( + final String path + ) + { + if ( File.separatorChar == SEPARATOR_DIRECTORY ) + { + return path; + } + + return path.replace( File.separatorChar, SEPARATOR_DIRECTORY ); + } + + public static String getFilename( final String path ) + { + return getTailingPath( path, 1 ); + } + + /** + * Returns an escaped name of the file name for linux. + * + * \ " $ => \\ \" \$ + * + * @param fileName + */ + public static String getEscapedName(String fileName) + { + Pattern sEscapePattern = Pattern.compile("([\\\\\"$])"); + return sEscapePattern.matcher(fileName).replaceAll("\\\\$1"); + } + + /** + * Return validation check of filename + * + * Windows does not allow \ / : * ? " <> | for file name + * + * Linux does not allow / for file name + * + * @param fileName file name to check + * + * @param os os type from OSChecker + * + * @return validation check result + */ + public static int isVaildName(String fileName, int os) + { + int result = IS_VALID_NAME; + if(fileName == null) + { + result = IS_NULL; + } + + if(fileName.length() == 0) + { + result = HAS_NO_NAME; + } + else + { + Pattern invalidPattern; + + switch(os) + { + case OSChecker.WINDOWS: + invalidPattern = Pattern.compile("([\\\\/:*?\"<>|])"); + break; + case OSChecker.LINUX: + default: + invalidPattern = Pattern.compile("([/])"); + } + + if(invalidPattern.matcher(fileName).find()) + { + result = HAS_INVALID_CHARACTER; + } + } + return result; + } + + /** + * Return validation check of filename for host os + * + * @param fileName file name to check + * + * @return validation check result + */ + public static boolean isVaildName(String fileName) + { + return isVaildName(fileName, OSChecker.getOSID()) == IS_VALID_NAME ? true : false; + } + + /** + * Return invalid filename characters + * + * @param os os type from OSChecker + * + * @return validation check result + */ + public static String getInvalidCharacters(int os) + { + switch(os) + { + case OSChecker.WINDOWS: + return "\\\\/:*?\"<>|"; + case OSChecker.LINUX: + return "/"; + default: + return "/"; + } + } + + /** + * Return invalid filename characters for host os + * + * @return validation check result + */ + public static String getInvalidCharacters() + { + return getInvalidCharacters(OSChecker.getOSID()); + } + + public static String addDoubleQuote(String str) + { + return "\""+ str + "\""; + } + + /** + * Extract file name without extension from full name + * + * @param nameWithExt file name with extension + * + * @return file name + */ + public static String getName( final String nameWithExt ) + { + if ( null == nameWithExt ) + { + throw new NullPointerException(); + } + + final int index = nameWithExt.lastIndexOf( '.' ); + + if ( index < 0 ) + { + return nameWithExt; + } + + return nameWithExt.substring( 0, index ); + } + + /** + * Extract file extension from full name + * + * @param nameWithExt file name with extension + * + * @return file extension + */ + public static String getExtension( final String nameWithExt ) + { + if ( null == nameWithExt ) + { + throw new NullPointerException(); + } + + final int index = nameWithExt.lastIndexOf( '.' ); + + if ( index < 0 ) + { + return ""; + } + + return nameWithExt.substring( index + 1 ); + } + + /** + * Compare two file path with canonical + * + * @param file1 file1 to compare + * @param file2 file2 to compare + * + * @return <code>true</code> if <code>file1</code> and <code>file2</code> have equal path + */ + public static boolean equals( final File file1, final File file2 ) + { + try + { + return ObjectUtil.equals( + getCanonicalPath( file1 ), + getCanonicalPath( file2 ) + ); + } catch ( final IOException e ) + { + throw new IllegalArgumentException(); + } + } + + + public static boolean equals( final String path1, final String path2 ) + { + return ObjectUtil.equals( path1, path2 ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/FilterIterator.java b/org.tizen.common/src/org/tizen/common/util/FilterIterator.java new file mode 100644 index 000000000..100223520 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/FilterIterator.java @@ -0,0 +1,158 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * FilterIterator. + * + * {@link Iterator} using filter method + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @param <E> + */ +public class +FilterIterator<E> +implements Iterator<E> +{ + /** + * Unfiltered iterator + */ + protected final Iterator<? extends E> impl; + + /** + * Acceptable element + */ + protected E acceptableElement; + + /** + * Constructor with array instance of type E + * + * @param array array to iterate + */ + public + FilterIterator( + final E[] array + ) + { + this( Arrays.asList( array ) ); + } + + /** + * Constructor with collection containing E object + * + * @param collection collection to iterate + */ + public + FilterIterator( + final Collection<? extends E> collection + ) + { + this.impl = ( null == collection )?null:collection.iterator(); + } + + /* (non-Javadoc) + * @see java.util.Iterator#hasNext() + */ + @Override + public + boolean + hasNext() + { + if ( null == this.impl ) + { + return false; + } + + while ( this.impl.hasNext() ) + { + final E element = this.impl.next(); + if ( isAcceptable( element ) ) + { + this.acceptableElement = element; + return true; + } + } + return false; + } + + /* (non-Javadoc) + * @see java.util.Iterator#next() + */ + @Override + public + E + next() + { + if ( null == this.impl ) + { + throw new NoSuchElementException(); + } + + return this.acceptableElement; + } + + /* (non-Javadoc) + * @see java.util.Iterator#remove() + */ + @Override + public + void + remove() + { + if ( null == this.impl ) + { + throw new NoSuchElementException(); + } + this.impl.remove(); + } + + /** + * Determine <code>element</code> is acceptable( not filtering ) + * + * @param element object to check + * + * @return boolean value if <code>element is acceptable + */ + protected + boolean + isAcceptable( + final E element + ) + { + if ( null == element ) + { + return false; + } + + return true; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java b/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java new file mode 100644 index 000000000..b43d60f9a --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java @@ -0,0 +1,180 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Jihoon Song <jihoon80.song@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Locale; +import java.util.Map; + +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.ui.plugin.AbstractUIPlugin; + +import freemarker.template.Configuration; +import freemarker.template.DefaultObjectWrapper; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +/** + * FreeMarkerUtil. + * + * Helper related to FreeMarker + * + * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core) + */ +public class FreeMarkerUtil { + + private final static String DEFAULT_ENCODING = "8859_1"; + + // Constructor + private FreeMarkerUtil() {} + + /** + * Get default initialized template configuration. + * + * @return Configuration + */ + public static Configuration getDefaultConfiguration() { + // initialize FreeMarker engine + Configuration cfg = new Configuration(); + cfg.setEncoding(Locale.getDefault(), DEFAULT_ENCODING); //$NON-NLS-1$ + cfg.setObjectWrapper(new DefaultObjectWrapper()); + + return cfg; + } + + /** + * Get initialized template configuration. + * + * @param activator be used for Plug-in based relative path. If this value is null, throws NullPointerException. + * @param relativeParentPath relative template's parent path in Plug-in Bundle. + * @return Configuration + * @throws URISyntaxException + * @throws IOException + */ + public static Configuration getConfiguration(AbstractUIPlugin activator, String relativeParentPath) + throws URISyntaxException, IOException { + Assert.notNull(activator); + Assert.notNull(relativeParentPath); + + Configuration cfg = getDefaultConfiguration(); + + // set template location in plug-in + URL templateFolderURL = activator.getBundle().getEntry(relativeParentPath); + if (templateFolderURL == null) { + throw new FileNotFoundException(); + } + + URI templateFolderURI = FileLocator.toFileURL(templateFolderURL).toURI(); + File templateFolder = new File(templateFolderURI); + + cfg.setDirectoryForTemplateLoading(templateFolder); + + return cfg; + } + + /** + * Generate document using freemarker template. + * + * @param root template data model + * @param cfg template configuration instance + * @param templateFile template file + * @param destination output file name + * @throws IOException + * @throws TemplateException + */ + public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, String destination) + throws IOException, TemplateException { + generateDocument(root, cfg, templateFile, new File( destination )); + } + + /** + * Generate document using freemarker template. + * + * @param root template data model + * @param cfg template configuration instance + * @param templateFile template file + * @param destinationFile will be used for internal stream like FileOutputStream. + * @throws IOException + * @throws TemplateException + */ + public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, File destinationFile) + throws IOException, TemplateException { + generateDocument(root, cfg, templateFile, new FileOutputStream( destinationFile )); + } + + /** + * Generate document using freemarker template. + * + * @param root template data model + * @param cfg template configuration instance + * @param templateFile template file + * @param outputStream will be used for internal writer like BufferedWriter and OutputStreamWriter. + * @throws IOException + * @throws TemplateException + */ + public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, OutputStream outputStream) + throws IOException, TemplateException { + generateDocument(root, cfg, templateFile, new BufferedWriter( new OutputStreamWriter( outputStream ) )); + } + + /** + * Generate document using freemarker template. + * + * @param root template data model + * @param cfg template configuration instance + * @param templateFile template file + * @param writer output writer + * @throws IOException + * @throws TemplateException + */ + public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, Writer writer) + throws IOException, TemplateException { + Assert.notNull(root); + Assert.notNull(cfg); + Assert.notNull(templateFile); + Assert.notNull(writer); + + Template template = cfg.getTemplate(templateFile); + + // generate document + try { + template.process(root, writer); + IOUtil.tryFlush(writer); + } finally { + IOUtil.tryClose(writer); + } + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java b/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java new file mode 100644 index 000000000..58db9e3a8 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java @@ -0,0 +1,120 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.browser.Browser; +import org.eclipse.swt.browser.LocationEvent; +import org.eclipse.swt.browser.LocationListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.ToolItem; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.help.IWorkbenchHelpSystem; +import org.tizen.common.CommonPlugin; + +public class HelpBrowser { + + private static final String HELP_PAGE_PREFIX = "help:/"; + private static final String BACK_ICON = "icons/back.gif"; + private static final String FORWARD_ICON = "icons/forward.gif"; + + private Browser browser; + + public Browser getBrowser() { + return browser; + } + + public HelpBrowser(Composite parent, int style) { + this(parent, style, false); + } + + public HelpBrowser(Composite parent, int style, boolean hasToolbar) { + if(hasToolbar == true) { + generateToolBar(parent); + } + this.browser = new Browser(parent, style); + GridData gd = new GridData(GridData.FILL_BOTH); + this.browser.setLayoutData(gd); + enableHelpPage(); + } + + private void generateToolBar(Composite parent) { + ToolBar toolbar = new ToolBar(parent, SWT.None); + + ToolItem backButton = new ToolItem(toolbar, SWT.PUSH); + Image backIcon = ImageUtil.getImage(CommonPlugin.PLUGIN_ID, BACK_ICON); + backButton.setImage(backIcon); + + ToolItem forwardButton = new ToolItem(toolbar, SWT.PUSH); + Image forwardIcon = ImageUtil.getImage(CommonPlugin.PLUGIN_ID, FORWARD_ICON); + forwardButton.setImage(forwardIcon); + + forwardButton.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + browser.forward(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + backButton.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + browser.back(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + + private void enableHelpPage() { + this.getBrowser().addLocationListener(new LocationListener() { + @Override + public void changing(LocationEvent event) { + String url = event.location; + if(url.startsWith(HELP_PAGE_PREFIX)) { + Browser browser = ((Browser)event.widget); + String tempUrl = url.substring(HELP_PAGE_PREFIX.length(), url.length()); + IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem(); + browser.setUrl(helpSystem.resolve(tempUrl, false).toString()); + } + } + @Override + public void changed(LocationEvent event) { + } + }); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/HostUtil.java b/org.tizen.common/src/org/tizen/common/util/HostUtil.java index a2e1b6871..012a60c49 100644..100755 --- a/org.tizen.common/src/org/tizen/common/util/HostUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/HostUtil.java @@ -24,356 +24,311 @@ */ package org.tizen.common.util; +import static org.tizen.common.util.IOUtil.tryClose; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; -import java.io.IOException; import java.io.InputStreamReader; -import java.net.InetAddress; import java.nio.channels.FileChannel; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.tizen.common.console.ConsoleManager; +import org.tizen.common.ui.view.console.ConsoleManager; public abstract class HostUtil{ - -// public static final String USER = System.getenv("USER"); -// public static final String USER_HOME = System.getenv("HOME"); - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ - public static final String FILE_SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$ - - private static final String PROC_PATH = "/proc"; //$NON-NLS-1$ - private static final String SHELL_COMMAND_LINUX= "/bin/sh"; //$NON-NLS-1$ - private static final String SHELL_COMMAND_WINDOW= "cmd"; //$NON-NLS-1$ - - public static boolean hasProcFile(String pid) { - if(pid==null||pid.equals("")) //$NON-NLS-1$ - return false; + + public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ + public static final String FILE_SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$ + + private static final String SHELL_COMMAND_LINUX= "/bin/sh"; //$NON-NLS-1$ + private static final String SHELL_COMMAND_WINDOW= "cmd"; //$NON-NLS-1$ + + public static String getContents(String filePath) { + BufferedReader input = null; + StringBuilder contents = new StringBuilder(); + String line = null; + + try { + input = new BufferedReader(new FileReader(filePath)); + while((line=input.readLine())!=null){ + contents.append(line); + contents.append(LINE_SEPARATOR); + } + }catch(Exception e) { +// e.printStackTrace(); + return null; + }finally{ + tryClose( input ); + } + + return contents.toString().trim(); + } - String pidFile = PROC_PATH+Path.SEPARATOR+pid; - return exists(pidFile); - } - public static boolean isMenuReady(String pid) { - if(pid==null||pid.equals("")) //$NON-NLS-1$ - return false; + public static boolean exists(String path) { + if( path == null || path.equals("") ) //$NON-NLS-1$ + return false; - String pidFile = PROC_PATH+Path.SEPARATOR+pid; - return exists(pidFile); - } + File file = new File( path ); - - public static String getContents(String filePath) { - BufferedReader input = null; - StringBuilder contents = new StringBuilder(); - String line = null; - - try { - input = new BufferedReader(new FileReader(filePath)); - while((line=input.readLine())!=null){ - contents.append(line); - contents.append(LINE_SEPARATOR); - } - }catch(Exception e) { -// e.printStackTrace(); - return null; - }finally{ - if(input!=null) - try { - input.close(); - } catch (IOException e) { - } - } - - return contents.toString().trim(); - } - - public static boolean isReachable(String ip) { - try { - return InetAddress.getByName(ip).isReachable(100); - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } + return file.exists(); + } - public static boolean exists(String path) { - if(path==null||path.equals("")) //$NON-NLS-1$ - return false; - - IPath ipath = new Path(path); - File file = ipath.toFile(); - - if(file!=null&&file.exists()) - return true; - else - return false; - } - - public static boolean execute(String command){ - Process proc = null; - Runtime runtime = Runtime.getRuntime(); - - String[] fullCommand = getCommand(command); - - int i = 0; - try { - proc= runtime.exec(fullCommand); - i = proc.waitFor(); - } catch (Exception e) { - e.printStackTrace(); - return false; - } finally{ - System.out.println("HostUtil execute - exit value : " + i); - if(proc!=null) - proc.destroy(); - } - - return i==0; - } - - public static boolean batchExecute(String command) - { - String[] fullCommand = getCommand(command); + public static boolean execute(String command){ + + if(command == null) { + return false; + } + Process proc = null; + Runtime runtime = Runtime.getRuntime(); + + String[] fullCommand = getCommand(command); + + int i = 0; + try { + proc= runtime.exec(fullCommand); + i = proc.waitFor(); + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally{ + System.out.println("HostUtil execute - exit value : " + i); + if(proc!=null) + proc.destroy(); + } + + return i==0; + } + + public static boolean batchExecute(String command) + { + if(command == null) { + return false; + } + String[] fullCommand = getCommand(command); - Runtime run = Runtime.getRuntime(); - Process p = null; - - try{ - p = run.exec(fullCommand); - StreamGobbler gb1 = new StreamGobbler(p.getInputStream()); - StreamGobbler gb2 = new StreamGobbler(p.getErrorStream()); - gb1.start(); - gb2.start(); - }catch(Exception e){ - e.printStackTrace(); - return false; - }finally{ - } - return true; - } + Runtime run = Runtime.getRuntime(); + Process p = null; + + int i = 0; + try{ + p = run.exec(fullCommand); + i = p.waitFor(); + StreamGobbler gb1 = new StreamGobbler(p.getInputStream()); + StreamGobbler gb2 = new StreamGobbler(p.getErrorStream()); + gb1.start(); + gb2.start(); + }catch(Exception e){ + e.printStackTrace(); + return false; + } + return i == 0; + } - /** - * Don't need for emultor install registration. - * using java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir) - * @param command - array containing the command to call and its arguments. - * @param envp - array of strings, each element of which has environment variable settings in format name=value. - * @param dir - Emultor path. - * @return success true, failed false. - */ - public static boolean batchExecute(String command, String[] envp, File dir) - { - String[] fullCommand = getCommand(command); + /** + * Don't need for emultor install registration. + * using java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir) + * @param command - array containing the command to call and its arguments. + * @param envp - array of strings, each element of which has environment variable settings in format name=value. + * @param dir - Emultor path. + * @return success true, failed false. + */ + public static boolean batchExecute(String command, String[] envp, File dir) + { + String[] fullCommand = getCommand(command); - Runtime run = Runtime.getRuntime(); - Process p = null; + Runtime run = Runtime.getRuntime(); + Process p = null; - StreamGobbler gb1 = null; - StreamGobbler gb2 = null; - try{ - p = run.exec(fullCommand, envp, dir); - gb1 = new StreamGobbler(p.getInputStream()); - gb2 = new StreamGobbler(p.getErrorStream()); - gb1.start(); - gb2.start(); - }catch(Exception e){ - e.printStackTrace(); - return false; - }finally{ - System.out.println(gb1.getResult()); - System.out.println(gb2.getResult()); - } - return true; - } + StreamGobbler gb1 = null; + StreamGobbler gb2 = null; + try{ + p = run.exec(fullCommand, envp, dir); + gb1 = new StreamGobbler(p.getInputStream()); + gb2 = new StreamGobbler(p.getErrorStream()); + gb1.start(); + gb2.start(); + }catch(Exception e){ + e.printStackTrace(); + return false; + }finally{ + System.out.println(gb1.getResult()); + System.out.println(gb2.getResult()); + } + return true; + } - public static String returnExecute(String command, String workingDir) { - BufferedReader input = null; - StringBuilder contents = new StringBuilder(); - String line = null; - - Process proc = null; - - String[] fullCommand = getCommand(command); - - try { - ProcessBuilder pb = new ProcessBuilder(); - pb.command(fullCommand); - if(workingDir != null) { - pb.directory(new File(workingDir)); - } - proc = pb.start(); - input = new BufferedReader(new InputStreamReader(proc.getInputStream())); - while((line=input.readLine())!=null){ - contents.append(line); - contents.append(LINE_SEPARATOR); - } - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally{ - if(proc!=null) - proc.destroy(); - if(input!=null) - try { - input.close(); - } catch (IOException e) { - } - } - - return contents.toString().trim(); - - } - - /** - * Show output messages while executes the command on console view - * @param command - Command to execute. - * @param viewName - View name showing messages while executes the command. - */ - public static void executeWithConsole(String command, String viewName) throws Exception { - BufferedReader input = null; + public static String returnExecute(String command, String workingDir) { + + if(command == null) { + return null; + } + BufferedReader input = null; + StringBuilder contents = new StringBuilder(); + String line = null; + + Process proc = null; + + String[] fullCommand = getCommand(command); + + try { + ProcessBuilder pb = new ProcessBuilder(); + pb.command(fullCommand); + if(workingDir != null) { + pb.directory(new File(workingDir)); + } + proc = pb.start(); + input = new BufferedReader(new InputStreamReader(proc.getInputStream())); + while((line=input.readLine())!=null){ + contents.append(line); + contents.append(LINE_SEPARATOR); + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally{ + tryClose( input ); + if(proc!=null) + { + proc.destroy(); + } + } + + return contents.toString().trim(); + + } + + /** + * Show output messages while executes the command on console view + * @param command - Command to execute. + * @param viewName - View name showing messages while executes the command. + */ + public static void executeWithConsole(String command, String viewName) throws Exception { + BufferedReader input = null; - String line = null; - - Process proc = null; - - String[] fullCommand = getCommand(command); - - ConsoleManager cm = new ConsoleManager( viewName, true ); - cm.clear(); - - try { - ProcessBuilder pb = new ProcessBuilder(); - pb.redirectErrorStream(true); - pb.command(fullCommand); - proc = pb.start(); - input = new BufferedReader(new InputStreamReader(proc.getInputStream())); - while((line=input.readLine())!=null){ - cm.println(line); - } - proc.waitFor(); - // abnormal termination - if (proc.exitValue() != 0) - throw new Exception("Failed to execute command: " + command); - } finally { - if(proc!=null) - proc.destroy(); - if(input!=null) - try { - input.close(); - } catch (IOException e) { - } - } - } - - public static String returnExecute(String command){ - - return returnExecute(command, null); - } - - public static String[] getCommand(String command){ - - if(OSChecker.isWindows()){ - return new String[]{SHELL_COMMAND_WINDOW,"/c",command}; //$NON-NLS-1$ - }else - { - return new String[]{SHELL_COMMAND_LINUX,"-c",command}; //$NON-NLS-1$ - } - } - - - public static boolean createFile(String path, String contents) { - BufferedWriter output = null; - try { - File file = new File(path); - - File folder = file.getParentFile(); - if(folder!=null) - folder.mkdirs(); - - file.createNewFile(); - - output = new BufferedWriter(new FileWriter(file)); - output.write(contents); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - }finally{ - if(output!=null) - try { - output.close(); - } catch (IOException e) { - } - } - } - - public static boolean removeFile(String path) { - File file = new File(path); - if (!file.exists()) - return false; - return file.delete(); - } - - /** - * @deprecated Use {@link FileUtil#copyTo(String, String)} instead. - */ - @Deprecated - public static boolean copyFile(String src, String des) throws Exception { - boolean canExecute = false; - File srcFile=new File(src); - File desFile=null; - FileInputStream fis=null; - FileOutputStream fos=null; - FileChannel fcin=null; - FileChannel fcout=null; - - canExecute = srcFile.canExecute(); - - desFile= new File(des); - File paths = new File(desFile.getAbsolutePath().substring(0, desFile.getAbsolutePath().lastIndexOf("/"))); //$NON-NLS-1$ - if (!paths.exists()) { - paths.mkdirs(); - } - - try { - fis= new FileInputStream(srcFile); - fos= new FileOutputStream(desFile); - fcin= fis.getChannel(); - fcout= fos.getChannel(); - - long size= fcin.size(); - fcin.transferTo(0, size, fcout); - desFile.setExecutable(canExecute); - } catch (FileNotFoundException e) { - e.printStackTrace(); - throw e; - } catch (IOException e) { - e.printStackTrace(); - throw e; - }finally{ - try { - fcout.close(); - fcin.close(); - fos.close(); - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - throw e; - } - } + String line = null; + + Process proc = null; + + String[] fullCommand = getCommand(command); + + ConsoleManager cm = new ConsoleManager( viewName, true ); + cm.clear(); + + try { + ProcessBuilder pb = new ProcessBuilder(); + pb.redirectErrorStream(true); + pb.command(fullCommand); + proc = pb.start(); + input = new BufferedReader(new InputStreamReader(proc.getInputStream())); + while((line=input.readLine())!=null){ + cm.println(line); + } + proc.waitFor(); + // abnormal termination + if (proc.exitValue() != 0) + throw new Exception("Failed to execute command: " + command); + } finally { + tryClose( input ); + if(proc!=null) + { + proc.destroy(); + } + } + } + + public static String returnExecute(String command){ + + return returnExecute(command, null); + } + + public static String[] getCommand(String command){ + + if(OSChecker.isWindows()){ + return new String[]{SHELL_COMMAND_WINDOW,"/c",command}; //$NON-NLS-1$ + }else + { + return new String[]{SHELL_COMMAND_LINUX,"-c",command}; //$NON-NLS-1$ + } + } + + /** + * @deprecated Use {@link FileUtil#createFile(File)}, + * {@link FileUtil#createFile(String)}, + * {@link FileUtil#createFile(String, String)} + * or + * {@link FileUtil#createTextFile(File, String, String)}, + * {@link FileUtil#createTextFile(String, String, String)}, + * {@link FileUtil#createTextFile(String, String, String, String)} + * and + * {@link FileUtil#createDirectory(File)}, + * {@link FileUtil#createDirectory(String)}, + * {@link FileUtil#createDirectory(String, String)} + * instead. + */ + @Deprecated + public static boolean createFile(String path, String contents) { + BufferedWriter output = null; + try { + File file = new File(path); + + File folder = file.getParentFile(); + if(folder!=null) + folder.mkdirs(); + + file.createNewFile(); + + output = new BufferedWriter(new FileWriter(file)); + output.write(contents); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + }finally{ + tryClose( output ); + } + } + + + /** + * @deprecated Use {@link FileUtil#copyTo(String, String)} instead. + */ + @Deprecated + public static boolean copyFile(String src, String des) throws Exception { + boolean canExecute = false; + File srcFile=new File(src); + File desFile=null; + FileInputStream fis=null; + FileOutputStream fos=null; + FileChannel fcin=null; + FileChannel fcout=null; + + canExecute = srcFile.canExecute(); + + desFile= new File(des); + File paths = new File(desFile.getAbsolutePath().substring(0, desFile.getAbsolutePath().lastIndexOf("/"))); //$NON-NLS-1$ + if (!paths.exists()) { + paths.mkdirs(); + } + + try { + fis= new FileInputStream(srcFile); + fos= new FileOutputStream(desFile); + fcin= fis.getChannel(); + fcout= fos.getChannel(); + + long size= fcin.size(); + fcin.transferTo(0, size, fcout); + desFile.setExecutable(canExecute); + }finally{ + tryClose( fcout, fcin, fos, fis ); + } - return true; - } - - public static boolean isLinux(){ - return Platform.getOS().equals(Platform.OS_LINUX); - } + return true; + } + } diff --git a/org.tizen.common/src/org/tizen/common/util/IOUtil.java b/org.tizen.common/src/org/tizen/common/util/IOUtil.java index 0dce62006..9fbd2e06f 100644 --- a/org.tizen.common/src/org/tizen/common/util/IOUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/IOUtil.java @@ -24,25 +24,361 @@ */ package org.tizen.common.util; +import java.io.ByteArrayOutputStream; import java.io.Closeable; +import java.io.Flushable; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.net.ServerSocket; +import java.net.Socket; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * IOUtil * @author Hyeongseok Heo {@literal<hyeongseok.heo@samsung.com>} + * BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * * @since Dec 9, 2011 */ public class IOUtil { - public static void close(Closeable closable) { - if( null != closable) { - try { - closable.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + private static final int BUFFER_SIZE = 8192; + + protected static final Logger logger = LoggerFactory.getLogger( IOUtil.class ); + + /** + * close closable objects. + * + * @param closeables object to be able to close + */ + public static void tryClose( final Object... closeables ) + { + if ( null == closeables ) + { + return ; + } + + for ( Object obj : closeables ) + { + if ( null == obj ) + { + continue; + } + try + { + if ( obj instanceof Closeable ) + { + ((Closeable) obj).close(); + } + else if ( obj instanceof Socket ) + { + ((Socket) obj).close(); + } + else if ( obj instanceof ServerSocket ) + { + ((ServerSocket) obj).close(); + } + } + catch ( final IOException e ) + { + } + } + } + + /** + * flush <code>Flushable</code>s + * + * @param flushables <code>Flushable</code>s to flush + */ + public static void tryFlush( final Flushable... flushables ) + { + if ( null == flushables ) + { + return ; + } + + for ( Flushable closeable : flushables ) + { + if ( null == closeable ) + { + continue; + } + try + { + closeable.flush(); + } + catch ( final IOException e ) + { + } + } + + } + + /** + * Redirect from <code>in</code> to <code>out</code> + * + * @param in {@link InputStream} + * @param out {@link OutputStream} + * + * @throws IOException occur exception when handling <code>in</code> or <code>out</code> + */ + public static + void + redirect( + final InputStream in, + final OutputStream out + ) + throws IOException + { + final byte[] buffer = new byte[BUFFER_SIZE]; + + int nRead = 0; + int totalBytes = 0; + while ( 0 < ( nRead = in.read( buffer ) ) ) + { + out.write( buffer, 0, nRead ); + totalBytes += nRead; + } + + logger.trace( "{} byte(s) wrote", totalBytes ); + + tryFlush( out ); + } + + /** + * Redirect from <code>reader</code> to <code>writer</code> + * + * @param reader {@link Reader} + * @param writer {@link Writer} + * + * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code> + */ + public static + void + redirect( + final Reader reader, + final Writer writer + ) + throws IOException + { + final char[] buffer = new char[BUFFER_SIZE]; + + int nRead = 0; + while ( 0 < ( nRead = reader.read( buffer ) ) ) + { + writer.write( buffer, 0, nRead ); + } + tryFlush( writer ); + } + + /** + * Redirect from <code>reader</code> to <code>writer</code> + * + * @param reader {@link Reader} + * @param writer {@link StringBuffer} + * + * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code> + */ + public static + void + redirect( + final Reader reader, + final StringBuffer writer + ) + throws IOException + { + final char[] buffer = new char[BUFFER_SIZE]; + + int nRead = 0; + while ( 0 < ( nRead = reader.read( buffer ) ) ) + { + writer.append( buffer, 0, nRead ); + } + } + + /** + * Redirect from <code>reader</code> to <code>writer</code> + * + * @param reader {@link Reader} + * @param writer {@link StringBuilder} + * + * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code> + */ + public static + void + redirect( + final Reader reader, + final StringBuilder writer + ) + throws IOException + { + if ( null == reader ) + { + return ; + } + final char[] buffer = new char[BUFFER_SIZE]; + + int nRead = 0; + while ( 0 < ( nRead = reader.read( buffer ) ) ) + { + writer.append( buffer, 0, nRead ); + } + } + + + /** + * Get and return byte array from {@link InputStream} + * + * @param in input stream to read byte array + * + * @return stored byte array + * + * @throws IOException If can't read byte from <code>in</code> + * + * @link {@link #getBytes(InputStream, boolean)} + */ + public static + byte[] getBytes( + final InputStream in + ) + throws IOException + { + return getBytes( in, false ); + } + + /** + * Get and return byte array from {@link InputStream} + * + * @param in input stream to read byte array + * @param bClose optional flag if close <code>in</code> after processing + * + * @return stored byte array + * + * @throws IOException If can't read byte from <code>in</code> + * + * @link {@link #redirect(InputStream, OutputStream)} + */ + public static + byte[] getBytes( + final InputStream in, + final boolean bClose + ) throws IOException + { + final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + + try + { + redirect( in, byteOut ); + + if ( bClose ) + { + tryClose( in ); } + + return byteOut.toByteArray(); } + finally + { + tryClose( byteOut ); + } + + } + + /** + * <p> + * Get and return string from {@link Reader} + * + * return empty string( "" ) if <code>reader</code> is <code>null</code> + * </p> + * + * @param reader reader to read string + * @return string to be accquired + * + * @throws IOException If can't read string from {@link Reader} + * + * @see #getString(Reader, boolean) + */ + public static + String getString( + final Reader reader + ) + throws IOException + { + return getString( reader, false ); + } - + + /** + * <p> + * Get and return string from {@link Reader} + * + * Return empty string( "" ) if <code>reader</code> is <code>null</code> + * </p> + * + * @param reader reader to read string + * @param bClose optional flag if close <code>in</code> after processing + * + * @return string to be accquired + * + * @throws IOException If can't read string from {@link Reader} + * + * @see #redirect(Reader, StringBuilder) + */ + public static + String + getString( + final Reader reader, + final boolean bClose + ) + throws IOException + { + final StringBuilder writer = new StringBuilder(); + try { + redirect( reader, writer ); + + if ( bClose ) + { + tryClose( reader ); + } + + return writer.toString(); + } + finally + { + tryClose( writer ); + } + + } + + /** + * <p> + * Get and return string from {@link InputStream} + * + * Return empty string ( "" ) if <code>in</code> is <code>null</code> + * + * @param in {@link InputStream} to read + * + * @return string to be accquired + * + * @throws IOException If can't read anything from {@link InputStream} + * + * @see #getString(Reader) + */ + public static + String + getString( + final InputStream in + ) + throws IOException + { + return getString( new InputStreamReader( in ) ); + } + + } diff --git a/org.tizen.common/src/org/tizen/common/util/ImageUtils.java b/org.tizen.common/src/org/tizen/common/util/ImageUtil.java index c22fd7828..49d85e29f 100644 --- a/org.tizen.common/src/org/tizen/common/util/ImageUtils.java +++ b/org.tizen.common/src/org/tizen/common/util/ImageUtil.java @@ -31,19 +31,73 @@ import org.eclipse.core.runtime.Plugin; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; +import org.osgi.framework.Bundle; +import org.tizen.common.SurrogateWithArgument; -public class ImageUtils { +public class ImageUtil { + public static class PlatformSurrogate { + public Bundle getBundle(String pluginID) { + return Platform.getBundle(pluginID); + } + } + + public static class PluginSurrogate { + public Bundle getBundle(Plugin plugin) { + return plugin.getBundle(); + } + } + + public static final String[] supportedImageExtension = { + "*.gif;*.png;*.jpeg;*.jpg;*.tiff;*.tif;*.ico;*.bmp;*.rle", // all supported format in SWT //$NON-NLS-1$ + "*.gif", // Graphics Interchange Format, including animated GIFs //$NON-NLS-1$ + "*.png", // Portable Network Graphics //$NON-NLS-1$ + "*.jpeg;*.jpg", // Joint Photographic Experts Group //$NON-NLS-1$ + "*.tiff;*.tif", // Tagged Image File Format //$NON-NLS-1$ + "*.ico", // Widows Icon //$NON-NLS-1$ + "*.bmp", // Windows Bitmap //$NON-NLS-1$ + "*.rle" // Windows Bitmap with run-length encoding //$NON-NLS-1$ + }; + + /** + * load image descriptor from <code>bundle</code> with <code>filePath</code> + * + * @param bundle {@link Bundle} + * @param filePath image file path + * + * @return loaded {@link ImageDescriptor} + */ + protected static + ImageDescriptor + getImageDescriptor( + final Bundle bundle, + final String filePath + ) + { + final URL url = bundle.getEntry( filePath ); + return ImageDescriptor.createFromURL( url ); + } + + protected static SurrogateWithArgument<Bundle, String> platformSurrogate = new SurrogateWithArgument<Bundle, String>() { + public Bundle getAdapter( final String pluginId ) + { + return Platform.getBundle( pluginId ); + } + }; + protected static SurrogateWithArgument<Bundle, Plugin> pluginSurrogate = new SurrogateWithArgument<Bundle, Plugin>() { + public Bundle getAdapter(Plugin plugin) { + return plugin.getBundle(); + } + }; + // get ImageDescriptor from Plugin ID (ID -> ImageDescriptor) public static ImageDescriptor getImageDescriptor(String pluginID, String filePath) { - URL url = Platform.getBundle(pluginID).getEntry(filePath); - return ImageDescriptor.createFromURL(url); + return getImageDescriptor( platformSurrogate.getAdapter(pluginID), filePath ); } // get ImageDescriptor from Activator Plugin (Activator -> ImageDescriptor) public static ImageDescriptor getImageDescriptor(Plugin plugin, String filePath) { - URL url = plugin.getBundle().getEntry(filePath); // $NON-NLS-1$ - return ImageDescriptor.createFromURL(url); + return getImageDescriptor( pluginSurrogate.getAdapter(plugin), filePath ); } // get Image from ImageDescriptor (ImageDescriptor -> Image) @@ -79,4 +133,4 @@ public class ImageUtils { ImageDescriptor descriptor = getImageDescriptor(pluginID, filePath); return getImageData(descriptor); } -}
\ No newline at end of file +} diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java b/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java new file mode 100644 index 000000000..bb8c3d1a0 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java @@ -0,0 +1,49 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import java.util.Collection; + +/** + * IteratingAcceptor. + * + * Filter logic containing iterface for {@link Collection} or array + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @param <T> arguement type + */ +public interface IteratingAcceptor<T> +{ + /** + * Check that <code>arg</code> is filtered or passed + * + * @param arg collection element + * + * @return <code>true</code> if <code>arg</code> is element to pass + */ + boolean accept( T arg ); + +} diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java b/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java new file mode 100644 index 000000000..6c29b90fa --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java @@ -0,0 +1,7 @@ +package org.tizen.common.util; + +import java.util.Iterator; + +public interface IteratingAdapter<T> { + public Iterator<T> adapt( T obj ); +} diff --git a/org.tizen.common/src/org/tizen/common/model/ITreeModel.java b/org.tizen.common/src/org/tizen/common/util/IteratingRunner.java index 50a7a1373..5136d99c4 100644 --- a/org.tizen.common/src/org/tizen/common/model/ITreeModel.java +++ b/org.tizen.common/src/org/tizen/common/util/IteratingRunner.java @@ -1,42 +1,47 @@ -/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.Collection;
-
-public interface ITreeModel
-{
- public void add(ITreeVO datas);
- public void add(Collection<ITreeVO> datas);
- public void remove(ITreeVO datas);
- public void remove(Collection<ITreeVO> datas);
- public ITreeVO[] getDatas();
- public void load(String fileName);
- public void save(String fileName);
- public void clear();
- public int size();
- public String getSourceName();
-}
+/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import java.util.Collection; + +/** + * IteratingRunner. + * + * Runner with argument for iteration of {@link Collection} or array + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @param <T> arguement type + */ +public interface IteratingRunner<T> +{ + /** + * Run with collection element <code>arg</code> + * + * @param arg collection element + */ + public void run( T arg ); + +} diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java b/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java new file mode 100644 index 000000000..c01337000 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java @@ -0,0 +1,27 @@ +package org.tizen.common.util; + +import java.util.Iterator; + +public class IteratingUtil { + public static <T> void iterate( T obj, IteratingAdapter<T> adapter, IteratingRunner<T> runner ) + { + if ( null == obj ) + { + return ; + } + + Iterator<T> iter = adapter.adapt( obj ); + if ( null == iter ) + { + return ; + } + while ( iter.hasNext() ) + { + T child = iter.next(); + runner.run( child ); + iterate( child, adapter, runner ); + } + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java b/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java index 68c3337ed..da15c1250 100644 --- a/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java +++ b/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java @@ -38,45 +38,52 @@ import java.net.ServerSocket; * <li> added getAvailableLocalPort method. * </ul> */ -public class LocalPortChecker { - public static boolean isPortAvailable(int port) { - if ((port < 0) && (port > 65535)) - return false; +public class LocalPortChecker +{ + + public static boolean isPortInRange( final int port ) + { + return ( 0 <= port ) && ( port < 65536 ); + + } + public static boolean isPortAvailable( final int port ) + { + if ( !isPortInRange( port ) ) + { + return false; + } ServerSocket socket = null; - try { - socket = new ServerSocket(port); + try + { + socket = new ServerSocket( port ); return true; - } catch (IOException e) { - return false; - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - // do nothing - } - } - } - } - - public static int getAvailableLocalPort(int inc,int portBase) { - int port = portBase; - if (isPortAvailable(port)) { - return port; } - - if ( (port+inc) > 65535) { - return -1; + catch ( final IOException e ) + { + return false; } - - while ((port < 65535) && !isPortAvailable(port)) { - port += inc; + finally + { + IOUtil.tryClose( socket ); } - - if (isPortAvailable(port)) - return port; - else - return -1; + } + + public static int + getAvailableLocalPort( + final int inc, + final int portBase + ) + { + for ( int port = portBase ; true ; port += inc ) + { + if ( !isPortInRange( port) ) + { + return -1; + } + if ( isPortAvailable( port ) ) { + return port; + } + } } } diff --git a/org.tizen.common/src/org/tizen/common/util/MapUtil.java b/org.tizen.common/src/org/tizen/common/util/MapUtil.java new file mode 100644 index 000000000..f721875af --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/MapUtil.java @@ -0,0 +1,219 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import static org.tizen.common.util.StringUtil.NULL_STRING; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * MapUtil. + * + * Helper related to {@link Map} + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class MapUtil +{ + /** + * protected constructor + */ + protected MapUtil() {} + + /** + * Return <code>map</code>'s size + * + * Return <code>0</code>, if <code>map</code> is <code>null</code> + * + * @param map {@link Map} to count elements + * + * @return the number of element in <code>map</code> + */ + public static + int + length( + final Map<?, ?> map + ) + { + if ( null == map ) + { + return 0; + } + return map.size(); + } + + + /** + * Check if <code>map</code> is empty + * + * Return <code>true</code>, if <code>map</code> is <code>null</code> or has no element + * + * @param map {@link Map} to check + * + * @return if map is empty + */ + public static + boolean + isEmpty( + final Map<?, ?> map + ) + { + return ( 0 == length( map ) ); + } + + /** + * Return {@link Map} for <code>keys</code> and <code>values</code> + * + * add i th object of <code>values</code> with i th object of <code>keys</code> as key + * + * @param <K> key type + * @param <V> value type + * @param keys keys to add + * @param values values to add + * + * @return {@link Map} containing <code>keys</code> - <code>values</code> pairs + */ + public static <K, V> + Map<K, V> + asMap( + final K[] keys, + final V[] values + ) + { + final HashMap<K, V> map = new HashMap<K, V>(); + if ( null == keys || null == values ) + { + return map; + } + + for ( int i=0, n=Math.min( keys.length, values.length ) ; i<n ; ++i ) + { + map.put( keys[i], values[i] ); + } + return map; + } + + + /** + * Return {@link Map} for <code>objs</code> + * + * <code>objs</code> is {@link Object[]} that each element is key-value pair. + * + * @param <A> key type + * @param <B> value type + * @param objs key-value pairs to add + * + * @return created {@link Map} + */ + @SuppressWarnings("unchecked") + public static <A extends Object, B extends Object> + Map<A, B> + asMap( + final Object[][] objs + ) + { + final HashMap<A, B> map = new HashMap<A, B>(); + for ( int i=0, n=ArrayUtil.size( objs ) ; i<n ; ++i ) + { + if ( 2 != objs[i].length ) + { + continue; + } + map.put( (A) objs[i][0], (B) objs[i][1] ); + } + return map; + } + + /** + * Add {@link Properties}'s key-value pairs to <code>map</code> + * + * @param props {@link Properties} to provide key-value pairs + * @param map {@link Map} to be added + */ + public static + void + mergePropertiesIntoMap( + final Properties props, + final Map<Object, Object> map + ) + { + if ( null == map ) + { + throw new NullPointerException(); + } + if ( null == props ) + { + return ; + } + + final Enumeration<?> en = props.propertyNames(); + while ( en.hasMoreElements() ) + { + final String key = (String) en.nextElement(); + map.put( key, props.getProperty( key ) ); + } + } + + /** + * Return string to present {@link Map} for human + * + * @param map {@link Map} to print out + * + * @return string of presentation + */ + public static + String + toString( + final Map<?, ?> map + ) + { + if ( null == map ) + { + return NULL_STRING; + } + + final StringBuilder buffer = new StringBuilder(); + buffer.append( "{" ); + + if ( !map.isEmpty() ) + { + buffer.append( "\n" ); + for ( final Object key : map.keySet() ) + { + buffer.append( "\t" ); + buffer.append( key.toString() ); + buffer.append( "=" ); + buffer.append( map.get( key ) ); + buffer.append( "\n" ); + } + } + buffer.append( "}" ); + return buffer.toString(); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/NotificationType.java b/org.tizen.common/src/org/tizen/common/util/NotificationType.java index 3e8d5a8a7..ede8c87f5 100644 --- a/org.tizen.common/src/org/tizen/common/util/NotificationType.java +++ b/org.tizen.common/src/org/tizen/common/util/NotificationType.java @@ -25,7 +25,7 @@ package org.tizen.common.util; import org.eclipse.swt.graphics.Image; -import org.tizen.common.cache.ImageCache; +import org.tizen.common.util.cache.ImageCache; public enum NotificationType { diff --git a/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java b/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java index 047425327..3944a1954 100644 --- a/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java +++ b/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java @@ -41,14 +41,13 @@ import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; -import org.tizen.common.cache.ColorCache; -import org.tizen.common.cache.FontCache; +import org.tizen.common.util.cache.ColorCache; +import org.tizen.common.util.cache.FontCache; public class NotifierDialog { @@ -133,7 +132,7 @@ public class NotifierDialog { // get the size of the drawing area Rectangle rect = _shell.getClientArea(); // create a new image with that size - Image newImage = new Image(Display.getDefault(), Math.max(1, rect.width), rect.height); + Image newImage = new Image(SWTUtil.getDisplay(), Math.max(1, rect.width), rect.height); // create a GC object we can use to draw with GC gc = new GC(newImage); @@ -315,14 +314,14 @@ public class NotifierDialog { } _shell.setAlpha(cur); - Display.getDefault().timerExec(FADE_TIMER, this); + SWTUtil.getDisplay().timerExec(FADE_TIMER, this); } catch (Exception err) { err.printStackTrace(); } } }; - Display.getDefault().timerExec(FADE_TIMER, run); + SWTUtil.getDisplay().timerExec(FADE_TIMER, run); } private static void startTimer(final Shell _shell) { @@ -340,7 +339,7 @@ public class NotifierDialog { } }; - Display.getDefault().timerExec(DISPLAY_TIME, run); + SWTUtil.getDisplay().timerExec(DISPLAY_TIME, run); } @@ -367,7 +366,7 @@ public class NotifierDialog { _shell.setAlpha(cur); - Display.getDefault().timerExec(FADE_TIMER, this); + SWTUtil.getDisplay().timerExec(FADE_TIMER, this); } catch (Exception err) { err.printStackTrace(); @@ -375,7 +374,7 @@ public class NotifierDialog { } }; - Display.getDefault().timerExec(FADE_TIMER, run); + SWTUtil.getDisplay().timerExec(FADE_TIMER, run); } } diff --git a/org.tizen.common/src/org/tizen/common/util/OSChecker.java b/org.tizen.common/src/org/tizen/common/util/OSChecker.java index 3331a46ac..9890ab0c6 100644 --- a/org.tizen.common/src/org/tizen/common/util/OSChecker.java +++ b/org.tizen.common/src/org/tizen/common/util/OSChecker.java @@ -26,6 +26,7 @@ package org.tizen.common.util; /** * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) + * @author Gyeongseok Seo {@literal <gyeongseok.seo@samsung.com>} (S-Core) * <ul> * <li> initial creation * <li> thanks to Yoon Kyung Koo @@ -35,12 +36,14 @@ public class OSChecker { // // OS ID constants // - public final static int WINDOWS = 0x0001; - public final static int MAC = 0x0002; - public final static int LINUX = 0x0004; - public final static int UNIX = 0x0008; - public final static int AIX = 0x0010; - public final static int SOLARIS = 0x0020; + public final static int WINDOWS = 0x0100; + public final static int WINDOWSXP = 0x0101; + public final static int WINDOWS7 = 0x0102; + public final static int MAC = 0x0200; + public final static int LINUX = 0x0400; + public final static int UNIX = 0x0800; + public final static int AIX = 0x1000; + public final static int SOLARIS = 0x2000; // // Vendor constants @@ -71,6 +74,11 @@ public class OSChecker { if (osName.indexOf("WINDOWS") >= 0) { osID |= OSChecker.WINDOWS; + if ( ObjectUtil.equals(osName, "WINDOWS XP") ) { + osID |= OSChecker.WINDOWSXP; + } else if ( ObjectUtil.equals(osName, "WINDOWS 7") ) { + osID |= OSChecker.WINDOWS7; + } } else if (osName.indexOf("MAC") >= 0) { osID |= OSChecker.MAC; } else if (osName.indexOf("LINUX") >= 0) { @@ -108,6 +116,13 @@ public class OSChecker { return ((osID & OSChecker.WINDOWS) > 0); } + public static boolean isWindowsXP() { + return (osID == OSChecker.WINDOWSXP); + } + public static boolean isWindows7() { + return (osID == OSChecker.WINDOWS7); + } + public static boolean isMAC() { return ((osID & OSChecker.MAC) > 0); } @@ -157,4 +172,14 @@ public class OSChecker { return (vendorID == 0); } + /* querying arch */ + public static boolean is64bit() { + boolean is64bit = false; + if ( OSChecker.isWindows() ) { + is64bit = (System.getenv("ProgramFiles(x86)") != null); + } else { + is64bit = (System.getProperty("os.arch").indexOf("64") != -1); + } + return is64bit; + } } diff --git a/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java b/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java new file mode 100644 index 000000000..3c0f2f8e6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java @@ -0,0 +1,411 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import static org.tizen.common.util.StringUtil.NULL_STRING; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Collection; + +/** + * ObjectUtil. + * + * Helper related to <code>Object</code> or generic logic + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class ObjectUtil { + + /** + * protected constructor + */ + protected ObjectUtil() {} + + /** + * Returns first non-null element in args + * <br> + * Returns null if no non-null element + * + * @param <T> arguments' type + * @param args arguments to check + * + * @return non-null element in <code>args</code> + */ + public static <T> T nvl( T... args ) + { + if ( null == args ) + { + return null; + } + + for ( final T arg : args ) + { + if ( null != arg ) + { + return arg; + } + } + return null; + } + + /** + * Hexadecimal IP + */ + private static String hexServerIP = null; + + /** + * Seed generator for GUID + */ + private static final SecureRandom SEEDER = new SecureRandom(); + + /** + * Compares two objects. + * <br> + * {@link Object#equals(Object)} is used for equality but this needs null check. + * <br> + * two object are equal if both are <code>null</code> + * <br> + * <pre> + * if ( null == obj1 ) { + * if ( obj1 == obj2 ) { + * ... + * } + * } else if ( obj1.equals( obj2 ) ) { + * ... + * } + * </pre> + * If you use this method + * <pre> + * if ( ObjectUtils.equals( obj1, obj2 ) ) { + * ... + * } + * </pre> + * Recursively compre if object is {@link Collection} or array + * <br> + * + * @param obj1 object1 to compare + * @param obj2 object2 to compare + * + * @return <code>true</code> if two object are equal + */ + @SuppressWarnings({ + "unchecked", "rawtypes" + }) + public static + boolean + equals( + final Object obj1, + final Object obj2 + ) + { + if ( obj1 == obj2 ) + { + return true; + } + if ( null == obj1 || null == obj2 ) + { + return false; + } + + if ( !obj1.getClass().isArray() || !obj2.getClass().isArray() ) + { + return obj1.equals( obj2 ); + } + + // in case of array + if ( obj1 instanceof boolean[] && obj2 instanceof boolean[] ) + { + return Arrays.equals( ( boolean[] ) obj1, ( boolean[] ) obj2 ); + } + else if ( obj1 instanceof byte[] && obj2 instanceof byte[] ) + { + return Arrays.equals( ( byte[] ) obj1, ( byte[] ) obj2 ); + } + else if ( obj1 instanceof char[] && obj2 instanceof char[] ) + { + return Arrays.equals( ( char[] ) obj1, ( char[] ) obj2 ); + } + else if ( obj1 instanceof double[] && obj2 instanceof double[] ) + { + return Arrays.equals( ( double[] ) obj1, ( double[] ) obj2 ); + } + else if ( obj1 instanceof float[] && obj2 instanceof float[] ) + { + return Arrays.equals( ( float[] ) obj1, ( float[] ) obj2 ); + } + else if ( obj1 instanceof int[] && obj2 instanceof int[] ) + { + return Arrays.equals( ( int[] ) obj1, ( int[] ) obj2 ); + } + else if ( obj1 instanceof long[] && obj2 instanceof long[] ) + { + return Arrays.equals( ( long[] ) obj1, ( long[] ) obj2 ); + } + else if ( obj1 instanceof short[] && obj2 instanceof short[] ) + { + return Arrays.equals( ( short[] ) obj1, ( short[] ) obj2 ); + } + else if ( obj1 instanceof Collection && obj2 instanceof Collection ) + { + return CollectionUtil.equals( (Collection) obj1, (Collection) obj2 ); + } + else if ( obj1 instanceof Object[] && obj2 instanceof Object[] ) + { + return CollectionUtil.equals( (Object[]) obj1, (Object[]) obj2 ); + } + return false; + } + + /** + * Convert byte[] to integer + * + * @param bytes byte array to convert + * + * @return converted integer + */ + public static + int + getInt( + final byte bytes[] + ) + { + int i= 0; + int j= 24; + for( int k=0 ; 0<=j ; ++k ) + { + int l = bytes[k] & 0xff; + i += l << j; + j -= 8; + } + return i; + } + + /** + * Pad <code>str</code> to string with <code>length</code> length + * + * Return <code>str</code> if string's length is greater than <code>length</code> + * + * The padding character is '0' + * + * @param str string to pad + * @param length length to pad + * + * @return padded string + */ + private static + String + padHex( + final String str, + final int length + ) + { + final StringBuilder buffer = new StringBuilder(); + for( int j=0, n=length-str.length() ; j<n ; ++j ) + { + buffer.append( '0' ); + } + buffer.append( str ); + return buffer.toString(); + } + + /** + * Convert <code>i</code> to hexadecimal with <code>j</code> length + * + * @param i decimal to convert + * @param j hexadecimal's length + * + * @return converted hexadecimal + */ + public static + String + hexFormat( + final int i, + final int j + ) + { + final String s = Integer.toHexString( i ); + return padHex( s, j ); + } + + + /** + * Create GUID with 32 bytes + * + * GUID is used for system( programe ) not human + * + * Structure + * +-----------------+--------------+----------------------+------------------+ + * | Current Time(8) | Server IP(8) | Object Hash Value(8) | Random Number(8) | + * +-----------------+--------------+----------------------+------------------+ + * + * @param obj object to hash + * @return create guid + */ + public static final + String + generateGUID( + final Object obj + ) + { + final StringBuilder guid = new StringBuilder( 32 ); + + // time + long timeNow = System.currentTimeMillis(); + int timeLow = (int) timeNow& 0xFFFFFFFF; + guid.append( hexFormat( timeLow, 8 ) ); + + // server IP + if ( null == hexServerIP ) + { + InetAddress localInetAddress = null; + try + { + // get the inet address + localInetAddress = InetAddress.getLocalHost(); + } + catch( final UnknownHostException uhe ) + { + try + { + localInetAddress = InetAddress.getByName( "localhost" ); + } + catch ( final UnknownHostException e ) + { + e.printStackTrace(); + return null; + } + } + + byte serverIP[] = localInetAddress.getAddress(); + + hexServerIP = hexFormat( getInt( serverIP ), 8 ); + } + guid.append( hexServerIP ); + + // object hash + guid.append( hexFormat( System.identityHashCode( obj ), 8 ) ); + + // random number + int node= -1; + synchronized( SEEDER ) + { + node = SEEDER.nextInt(); + } + guid.append( hexFormat( node, 8 ) ); + return guid.toString(); + } + + /* Serialize / Deserialize */ + /** + * Serialize object + * + * @param obj object to serialize + * + * @return serialized byte array + * + * @throws IOException If serialization is fail + * + * @see ObjectOutputStream#writeObject( Object ) + */ + public static + byte[] + serialize( + final Object obj + ) + throws IOException + { + final ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + final ObjectOutputStream objOut = new ObjectOutputStream( byteOut ); + objOut.writeObject( obj ); + return byteOut.toByteArray(); + } + + /** + * Deserialize byte array + * + * @param bytes bytes to deserialize + * + * @return Deserialized object + * + * @throws IOException If deserialization is fail + * + * @throws ClassNotFoundException If No class + * + * @see ObjectInputStream#readObject() + */ + public static + Object + deserialize( + final byte[] bytes + ) + throws IOException, ClassNotFoundException + { + Assert.notNull( bytes, "bytes must not be null" ); + final ByteArrayInputStream byteIn = new ByteArrayInputStream( bytes ); + final ObjectInputStream objIn = new ObjectInputStream( byteIn ); + return objIn.readObject(); + } + + /** + * Create and return object's simple name + * + * Use 4 hash value instead of 8 hash value + * + * @param obj object to convert + * + * @return textual string for <code>obj</code> + */ + public static + String + toString( + final Object obj + ) + { + if ( null == obj ) + { + return NULL_STRING; + } + final StringBuilder builder = new StringBuilder(); + builder.append( obj.getClass().getSimpleName() ); + builder.append( '@' ); + int hash = obj.hashCode(); + + for ( int i = 8 ; i>=0 ; i-=8 ) + { + StringUtil.appendHexa( builder, 0xFF & ( hash >> i ) ); + } + + + return builder.toString(); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java b/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java new file mode 100644 index 000000000..6d91b9430 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java @@ -0,0 +1,183 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; + +/** + * ParsingUtil. + * + * Helper related to parsing of textual implication + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class ParsingUtil +{ + + /** + * semantic <code>true</code> + */ + protected static final Collection<String> BOOLEAN_TRUE = + Collections.unmodifiableCollection( new HashSet<String>( Arrays.asList( + "1", "yes", "y", "true", "t" + ) ) ); + + /** + * sematic <code>false</code> + */ + protected static final Collection<String> BOOLEAN_FALSE = + Collections.unmodifiableCollection( new HashSet<String>( Arrays.asList( + "no, n", "false", "f", "0" + ) ) ); + + /** + * parse text and convert to <code>boolean</code> + * + * return <code>defaultValue</code> if can't parse or convert + * + * @param value string to parse + * @param defaultValue default value when exception case + * + * @return converted <code>boolean</code> value + */ + public static + boolean + parseBoolean( + final String value, + final boolean defaultValue + ) + { + if ( null == value ) + { + return defaultValue; + } + + final String safe = StringUtil.trim( value ).toLowerCase(); + return ((defaultValue)?BOOLEAN_FALSE:BOOLEAN_TRUE).contains( safe ) ^ defaultValue; + + } + + /** + * parse text and convert to <code>int</code> + * + * return <code>defaultValue</code> if can't parse or convert + * + * @param value string to parse + * @param defaultValue default value when exception case + * + * @return converted <code>int</code> value + */ + public static + int parseInt( + final String value, + final int defaultValue + ) + { + if ( null == value ) + { + return defaultValue; + } + + final String trimmed = StringUtil.trim( value ); + try + { + return Integer.decode( trimmed ); + } catch ( final Throwable e ) + { + return defaultValue; + } + } + + /** + * parse text and convert to <code>long</code> + * + * return <code>defaultValue</code> if can't parse or convert + * + * @param value string to parse + * @param defaultValue default value when exception case + * + * @return converted <code>long</code> value + */ + public static + long + parseLong( + final String value, + final long defaultValue + ) + { + if ( null == value ) + { + return defaultValue; + } + + final String trimmed = StringUtil.trim( value ); + try + { + return Long.decode( trimmed ); + } catch ( final Throwable e ) + { + return defaultValue; + } + + } + + /** + * parse text and convert to <code>double</code> + * + * return <code>defaultValue</code> if can't parse or convert + * + * @param value string to parse + * @param defaultValue default value when exception case + * + * @return converted <code>double</code> value + */ + public static + double + parseDouble( + final String value, + final double defaultValue + ) + { + if ( null == value ) + { + return defaultValue; + } + + final String trimmed = StringUtil.trim( value ); + try + { + return Double.valueOf( trimmed ); + } + catch( final Throwable e ) + { + return defaultValue; + } + + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/PluginUtil.java b/org.tizen.common/src/org/tizen/common/util/PluginUtil.java new file mode 100644 index 000000000..a451c4877 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/PluginUtil.java @@ -0,0 +1,105 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Kangho Kim <kh5325.kim@samsung.com> +* Ho Namkoong <ho.namkoong@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.Platform; +import org.tizen.common.Surrogate; + +/** + * PluginUtil + * + * This is a util class for handle extension points of the plugins. + * + * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core) + */ +public class PluginUtil { + + protected static Surrogate<IExtensionRegistry> platformSurrogate = new Surrogate<IExtensionRegistry>() { + public IExtensionRegistry getAdapter() + { + return Platform.getExtensionRegistry(); + } + }; + + /** + * Return classes of specific extension point id. + * @param extPointId - extension point id. + * @return object array of classes of extPointId. + */ + public static Object[] loadClasses(String extPointId) throws CoreException { + IExtensionRegistry registry = platformSurrogate.getAdapter(); + IExtensionPoint ep = registry.getExtensionPoint(extPointId ); + IExtension[] exts = ep.getExtensions(); + List<Object> classList = new ArrayList<Object>(); + + for ( IExtension ext : exts ) + { + IConfigurationElement[] configs = ext.getConfigurationElements(); + + for ( final IConfigurationElement config : configs ) + { + Object cls = (Object) config.createExecutableExtension( "class" ); + classList.add(cls); + } + } + + return classList.toArray(); + } + + /** + * Return class of specific class id which extends specific extension point id. + * @param extPointId - extension point id. + * @param classId - class id. + * @return object class of specific class id which extends specific extension point id. + */ + public static Object loadClass(String extPointId, String classId) throws CoreException { + IExtensionRegistry registry = platformSurrogate.getAdapter(); + IExtensionPoint ep = registry.getExtensionPoint(extPointId ); + IExtension[] exts = ep.getExtensions(); + + for ( IExtension ext : exts ) + { + IConfigurationElement[] configs = ext.getConfigurationElements(); + + for ( final IConfigurationElement config : configs ) + { + String id = config.getAttribute("id"); + if(id != null && id.equals(classId)) { + return (Object) config.createExecutableExtension( "class" ); + } + } + } + return null; + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java b/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java new file mode 100644 index 000000000..31acf7d30 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java @@ -0,0 +1,199 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Jihoon Song <jihoon80.song@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import java.util.Map; + +import org.eclipse.core.resources.ICommand; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.tizen.common.util.log.Logger; + +/** + * ProjectUtil. + * + * Helper related to the Eclipse Project (.project) + * + * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core) + */ +public class ProjectUtil { + + /** + * Null safety project description getter. If project is null, return null. + * @param project + * @return IProjectDescription + * @throws CoreException + */ + public static IProjectDescription getDescription(IProject project) throws CoreException { + return (project != null) ? project.getDescription() : null; + } + + /** + * Null safety project build specification getter + * @param project + * @return ICommand[] + * @throws CoreException + */ + public static ICommand[] getBuildSpec(IProject project) throws CoreException { + IProjectDescription description = getDescription( project ); + return (description != null) ? description.getBuildSpec() : new ICommand[0]; + } + + /** + * Build specification setter + * @param project + * @param commands + * @param monitor a progress monitor, or <code>null</code> if progress reporting is not desired + * @throws CoreException + */ + public static void setBuildSpec(IProject project, ICommand[] commands, IProgressMonitor monitor) + throws CoreException { + IProjectDescription description = getDescription( project ); + if ( description != null ) { // if project or project description is not null + description.setBuildSpec( commands ); + project.setDescription( description, monitor ); + } + } + + /** + * Null safety build command adder + * @param oldCommands + * @param newCommand + * @return ICommand[] + */ + public static ICommand[] addCommand(ICommand[] oldCommands, ICommand newCommand) { + // if newCommand is Null + if ( newCommand == null ) { + if ( oldCommands == null ) { // if argument is Null both, return 0-based array + return new ICommand[0]; + } else { + return oldCommands; + } + } + + // create expanded commands + ICommand[] newCommands; + if ( oldCommands != null ) { + newCommands = new ICommand[ oldCommands.length + 1 ]; + System.arraycopy( oldCommands, 0, newCommands, 0, oldCommands.length ); + } else { + newCommands = new ICommand[ 1 ]; + } + + // add new command to last index + newCommands[ newCommands.length - 1 ] = newCommand; + + return newCommands; + } + + /** + * Null safety build command finder. If not found, return null. + * @param commands + * @param builderID + * @return ICommand + */ + public static ICommand findCommand(ICommand[] commands, String builderID) { + if ( commands != null ) { + for (ICommand command : commands) { + String builderName = command.getBuilderName(); + if ( builderName != null && builderName.equals( builderID ) ){ + return command; + } + } + } + + return null; + } + + /** + * Null safety build command creater. If project or project description is null, return null. + * @param project + * @return ICommand + * @throws CoreException + */ + public static ICommand newCommand(IProject project) throws CoreException { + IProjectDescription description = getDescription( project ); + return (description != null) ? description.newCommand() : null; + } + + /** + * Specific build command adder with arguments. If builder ID already exist or is null, ignore this process. + * @param project + * @param builderID a builder name + * @param args a table of command arguments (keys and values must both be of type <code>String</code>), or <code>null</code> + * @param monitor a progress monitor, or <code>null</code> if progress reporting is not desired + */ + public static void setBuildCommandWithArgument(IProject project, String builderID, + Map<String, String> args, IProgressMonitor monitor) { + if ( builderID == null ) { // If builder ID is null + return ; + } + + try { + ICommand[] commands = getBuildSpec( project ); + + ICommand findedCommand = findCommand( commands, builderID ); + if ( findedCommand != null ) { // If builder ID already exist + return; + } + + ICommand command = newCommand( project ); + if ( command == null ) { + return; + } + + command.setBuilderName( builderID ); + command.setArguments( args ); + + ICommand[] newCommands = addCommand( commands, command ); + setBuildSpec( project, newCommands, monitor ); + } catch (CoreException e) { + Logger.log(e); + } + } + + /** + * Arguments getter in specific build command. If not found, return null. + * @param project + * @param builderID + * @return a table of command arguments (key type : <code>String</code> value type : <code>String</code>), or <code>null</code> + */ + public static Map<String, String> getBuildCommandArgument(IProject project, String builderID) { + try { + ICommand[] commands = getBuildSpec( project ); + ICommand command = findCommand( commands, builderID ); + if ( command != null ) { + return command.getArguments(); + } + } catch (CoreException e) { + Logger.log(e); + } + + return null; + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java b/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java index 2f7ac97b4..9e338c3ca 100644 --- a/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java @@ -24,11 +24,12 @@ */ package org.tizen.common.util; +import static org.tizen.common.util.IOUtil.tryClose; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; @@ -52,11 +53,7 @@ public abstract class PropertyUtil { } catch (Exception e) { e.printStackTrace(); } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - } + tryClose( reader ); } return props; } @@ -68,11 +65,7 @@ public abstract class PropertyUtil { } catch (Exception e) { e.printStackTrace(); } finally { - if (inputStream != null) - try { - inputStream.close(); - } catch (IOException e) { - } + tryClose( inputStream ); } return props; } @@ -84,11 +77,7 @@ public abstract class PropertyUtil { e.printStackTrace(); return false; } finally { - if (outputStream != null) - try { - outputStream.close(); - } catch (IOException e) { - } + tryClose( outputStream ); } return true; } @@ -103,11 +92,7 @@ public abstract class PropertyUtil { e.printStackTrace(); return false; } finally { - if (writer != null) - try { - writer.close(); - } catch (IOException e) { - } + tryClose( writer ); } return true; } diff --git a/org.tizen.common/src/org/tizen/common/util/SWTRunner.java b/org.tizen.common/src/org/tizen/common/util/SWTRunner.java new file mode 100755 index 000000000..ed2868242 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/SWTRunner.java @@ -0,0 +1,44 @@ +package org.tizen.common.util;
+
+import org.tizen.common.Cabinet;
+
+abstract public class
+SWTRunner<T>
+implements Runnable, Cabinet<T>
+{
+ protected T data;
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.Cabinet#getData()
+ */
+ @Override
+ public
+ T
+ getData()
+ {
+ return data;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.Cabinet#setData(java.lang.Object)
+ */
+ @Override
+ public
+ void
+ setData(
+ final T data
+ )
+ {
+ this.data = data;
+ }
+
+ @Override
+ public void run()
+ {
+ setData( process() );
+ }
+
+ abstract protected T process();
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/SWTUtil.java b/org.tizen.common/src/org/tizen/common/util/SWTUtil.java index e9c6f1981..4ee8c7893 100644..100755 --- a/org.tizen.common/src/org/tizen/common/util/SWTUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/SWTUtil.java @@ -26,29 +26,206 @@ package org.tizen.common.util; import java.awt.Dimension; import java.awt.Toolkit; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.Resource; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; +import org.tizen.common.Cabinet; +import org.tizen.common.ui.TableToolTipListener; +@SuppressWarnings("restriction") public class SWTUtil { + + private SWTUtil() {} + // 2012-04-25 + @Deprecated public static final String HTML_EXTENSIONS[] = { "html", "htm", "shtml", "shtm", "xhtml"}; + + protected static final Collection<?> HTML_EXTENSIONS2 = + Collections.unmodifiableCollection( new HashSet<Object>( Arrays.asList( HTML_EXTENSIONS ) ) ); + + /** + * return {@link Display} in context + * + * return new {@link Display} if no {@link Display} in context + * + * @return SWT {@link Display} simply + * + * @see Display#getCurrent() + * @see Display#getDefault(); + */ + public static Display getDisplay() + { + Display dp = Display.getCurrent(); + if ( null != dp ) + { + return dp; + } + + return Display.getDefault(); + } + + /** + * <p> + * Return active {@link Shell} in context + * </p> + * @return active {@link Shell} + * + * @see #getDisplay() + */ + public static Shell getActiveShell() + { + final Display dp = getDisplay(); + if ( null == dp ) + { + return null; + } + + return dp.getActiveShell(); + } + + /** + * execute {@link Cabinet#run()} and reeturn the result + * + * @param runnable object to execute + * + * @return result to execute + */ + public static + <T> + T + exec( + final Cabinet<T> runnable + ) + { + syncExec( (Runnable) runnable ); + + return runnable.getData(); + } + + /** + * execute {@link Runnable} in SWT thread synchronously + * + * @param runnable object to execute + */ + public static void syncExec( final Runnable runnable ) + { + syncExec( getDisplay(), runnable ); + } + + /** + * execute {@link Runnable} in SWT thread synchronously + * + * @param dp SWT <code>Display</code> + * @param runnable object to execute + */ + public static void syncExec( final Display dp, final Runnable runnable ) + { + dp.syncExec( runnable ); + } + + /** + * execute {@link Runnable} in SWT thread asynchronously + * + * @param runnable object to execute + */ + public static void asyncExec( final Runnable runnable ) + { + asyncExec( getDisplay(), runnable ); + } + + /** + * execute {@link Runnable} in SWT thread asynchronously + * + * @param dp SWT <code>Display</code> + * @param runnable object to execute + */ + public static void asyncExec( final Display dp, final Runnable runnable ) + { + dp.asyncExec( runnable ); + } + + /** + * dispose {@link Widget}s + * + * @param disposables {@link Widget}s to dispose + */ + public static void tryDispose( final Widget... disposables ) + { + if ( null == disposables ) + { + return ; + } + + for ( final Widget disposable : disposables ) + { + if ( null == disposable || disposable.isDisposed() ) + { + continue; + } + + disposable.dispose(); + } + } + + /** + * dispose {@link Resource}s + * + * @param disposables {@link Resource}s to dispose + */ + public static void tryDispose( final Resource... disposables ) + { + if ( null == disposables ) + { + return ; + } + + for ( final Resource disposable : disposables ) + { + if ( null == disposable || disposable.isDisposed() ) + { + continue; + } + + disposable.dispose(); + } + } /** * Creates SWT <code>Text</code> for input limited digit. @@ -80,6 +257,7 @@ public class SWTUtil { /** * Creates SWT <code>ScrolledComposite</code>. + * * @param width the minimum width or 0 for default width (0 is screen width) * @param height the minimum height or 0 for default height (0 is screen height) * @return <code>ScrolledComposite</code> @@ -103,6 +281,24 @@ public class SWTUtil { return sc; } + + /** + * Get current active page. + * + * return null if no active page + * + * @return active page + */ + public static IWorkbenchPage getActivePage() + { + final IWorkbenchWindow window = ViewUtil.getWorkbenchWindow(); + + if ( null == window ) + { + return null; + } + return window.getActivePage(); + } /** * Get current active editor. @@ -111,21 +307,15 @@ public class SWTUtil { * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) */ public static IEditorPart getActiveEditor() { - IWorkbenchWindow window = ViewUtil.getWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - - if(page == null){ - return null; - } - - IEditorPart editor = page.getActiveEditor(); - if(editor == null){ + final IWorkbenchPage page = getActivePage(); + if(page == null ) + { return null; } - return editor; + return page.getActiveEditor(); } - + /** * Get editor of file extension. * @@ -175,17 +365,9 @@ public class SWTUtil { * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) */ public static boolean isHtmlFile(String fullName) { - String fileExt = FileUtil.getFileExtension(fullName); - if (fileExt == null) { - return false; - } + String fileExt = StringUtil.nvl( FileUtil.getFileExtension(fullName) ); - for (String htmlExt : HTML_EXTENSIONS) { - if (htmlExt.equalsIgnoreCase(fileExt)) { - return true; - } - } - return false; + return HTML_EXTENSIONS2.contains( fileExt.toLowerCase() ); } /** @@ -239,4 +421,72 @@ public class SWTUtil { return projectPath; } -}
\ No newline at end of file + + public static void addTableToolTipListener(Table table, TableToolTipListener listener) { + listener.setTable(table); + table.addListener(SWT.MouseMove, listener); + table.addListener(SWT.MouseWheel, listener); + table.addListener(SWT.Dispose, listener); + table.addListener(SWT.MouseHover, listener); + } + + /** + * Expands tree and its sub treeitems. + * + * @param tree target tree to expand. + * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core) + */ + public static void expandTree(Tree tree) { + if(tree == null) { + return; + } + for(TreeItem treeitem: tree.getItems()) { + expandTreeItem(treeitem); + } + } + + private static void expandTreeItem(TreeItem treeItem) { + Stack<TreeItem> treeStack = new Stack<TreeItem>(); + treeStack.add(treeItem); + TreeItem selectedItem = null; + + do { + selectedItem = treeStack.pop(); + selectedItem.setExpanded(true); + + if(selectedItem.getItems() != null && selectedItem.getItemCount() != 0) { + for (TreeItem childItem : selectedItem.getItems()) { + treeStack.add(childItem); + } + } + } while (!treeStack.isEmpty()); + } + + /** + * Make error dialog which prints stack trace of the throwable + * + * @param title title of the dialog + * @param msg message of the dialog + * @param t throwable diaog prints out + * @param shell parent shell of this dialog + * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core) + */ + public static void errorDialogWithStackTrace(String title, String msg, Throwable t, String pluginId, Shell shell) { + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + + final String trace = sw.toString(); + + List<Status> childStatuses = new ArrayList<Status>(); + + for(String line: trace.split("\n")) { + childStatuses.add(new Status(IStatus.ERROR, pluginId, line)); + } + + MultiStatus ms = new MultiStatus(pluginId, IStatus.ERROR, childStatuses.toArray(new Status[] {}), t.getLocalizedMessage(), t); + + ErrorDialog.openError(shell, "Error Dialog", msg, ms); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java b/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java new file mode 100644 index 000000000..4e2545632 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java @@ -0,0 +1,76 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* Gun Kim <gune.kim@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ + +package org.tizen.common.util; + +import java.io.File; + +import org.tizen.common.core.application.InstallPathConfig; +import org.tizen.sdblib.IDevice; + +/** + * SdbCommandUtil. + * + * sdb helper + * + * @author Gun Kim{@literal <gune.kim@samsung.com>} (S-Core) + */ +public class SdbCommandUtil { + + /** + * push file to device + * + * @param device + * + * @param source source file path + * + * @param dest destination file path + */ + public static boolean filePush(IDevice device, String source, String dest){ + final String command_format = InstallPathConfig.getSDBPath() + " -s %s push %s %s "; + if ( device == null ) { + return false; + } + + if ( !(new File(source).exists()) ) { + return false; + } + + String command = String.format(command_format, device.getSerialNumber(), source, dest); + if (OSChecker.isUnix() ) { + command += "1>/dev/null"; + } + else if (OSChecker.isWindows() ) { + command += "1>NUL"; + } + String command_result = HostUtil.returnExecute(command); + + if ( "".equals(command_result)) { + return true; + } + + return false; + } +}
\ No newline at end of file diff --git a/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java b/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java index deae67722..da2532407 100644..100755 --- a/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java +++ b/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java @@ -24,6 +24,8 @@ */ package org.tizen.common.util; +import static org.tizen.common.util.IOUtil.tryClose; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -50,23 +52,26 @@ public class StreamGobbler extends Thread public void run() { StringBuffer buffer = new StringBuffer(); + BufferedReader br = null; try { synchronized (synchronizer) { - BufferedReader br = new BufferedReader(new InputStreamReader(is)); + br = new BufferedReader(new InputStreamReader(is)); String line; while ( (line = br.readLine()) != null) { buffer.append(line); buffer.append("\n"); if ( os != null ) + { os.write( (line + "\n").getBytes()); + } } - br.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { result = buffer.toString(); + tryClose( br ); } } public String getResult() { diff --git a/org.tizen.common/src/org/tizen/common/util/StringUtil.java b/org.tizen.common/src/org/tizen/common/util/StringUtil.java index c7ccee27e..8b97822af 100644..100755 --- a/org.tizen.common/src/org/tizen/common/util/StringUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/StringUtil.java @@ -28,10 +28,14 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; +import org.tizen.common.util.log.Logger; + /** * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) * <ul> @@ -41,57 +45,170 @@ import java.util.StringTokenizer; * @author gyeongseok.seo@samsung.com, S-Core Inc. * <ul> * <li> added split method. + * <li> added removeStart method. * </ul> */ -public class StringUtil { - public static String trimToNull(String s) { - return trimToNull(s, null); - } +public class StringUtil +{ + /** + * Empty String + */ + public static final String EMPTY_STRING = ""; - public static String trimToNull(String s, String def) { - if (s == null) { - return def; - } + /** + * Textual string for <code>null</code> + */ + public static final String NULL_STRING = "<<null>>"; - String t = s.trim(); - if (t.length() == 0) { - return def; - } + /** + * Textual string for empty byte array + */ + public static final String EMPTY_BYTES_STRING = "<<EMPTY BYTES>>"; + + /** + * Line separator string + */ + public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ); + + /** + * TAB string + */ + public static final String TAB = "\t"; + + /* Dump Format */ + protected static char CONTROL_CHARS_SHOWER = '.'; + + /** + * Hexa decimal conversion map + */ + protected static final char[] HEXA_CHARS = new char[] { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + /** + * The number how many bytes is in int + */ + protected static final int N_INT_BY_BYTE = 4; + + /** + * The number how many characters is print out in a line + */ + protected static final int WIDTH_PER_LINE = 16; + + /** + * Character to express for control( Human can't control character and control character break log format ) + */ + protected static char TWO_BYTES_CHARS_SHOWER = '?'; + + /** + * Return meaningful value of <code>str</code> + * + * Return <code>null</code> if <code>str</code> has no implication + * + * @param str string to check + * + * @return meaningful string + * + * @see #trimToNull(String, String) + */ + public static + String + trimToNull( + final String str + ) + { + return trimToNull(str, null); + } - return t; + /** + * Return meaningful value of <code>str</code> + * + * Return <code>def</code> if <code>str</code> has no implication + * + * @param str string to check + * + * @return meaningful string + * + * @see #getMeaningful(String) + * @see #isEmpty(CharSequence) + */ + public static String trimToNull(String str, String def) { + final String meaningful = getMeaningful( str ); + return isEmpty( meaningful )?def:meaningful; } - public static InputStream stringToInputStream(String src) { - if (src == null) { + /** + * Convert <code>src</code> to {@link InputStream} + * + * @param src string to convert + * + * @return {@link InputStream} containing <code>src</code> + */ + public static + InputStream + toInputStream( + final String src + ) + { + if ( null == src ) + { return null; } - return new ByteArrayInputStream(src.getBytes()); + return new ByteArrayInputStream( src.getBytes() ); } - public static String[] split(String s, String delim) { - List<String> list = new ArrayList<String>(); - StringTokenizer st = new StringTokenizer(s, delim); - while (st.hasMoreTokens()) { - list.add(st.nextToken()); + /** + * Split <code>str</code> with <code>delimiters</code> + * + * @param str string to split + * @param delimiters delimiters to split with + * + * @return strings to be split + */ + public static + String[] split( + final String str, + final String delimiters + ) + { + final List<String> list = new ArrayList<String>(); + final StringTokenizer tokenizer = new StringTokenizer( str, delimiters ); + while ( tokenizer.hasMoreTokens() ) + { + list.add( tokenizer.nextToken() ); } return (String[]) list.toArray(new String[0]); } - public static String getOnlyNumerics(String str) { - if (str == null) { + /** + * @param str + * @return + */ + public static String getOnlyNumerics( + final String str + ) + { + if ( null == str ) + { return null; } - char c; - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < str.length() ; i++) { - c = str.charAt(i); - if (Character.isDigit(c)) { - sb.append(c); + ArrayUtil.iterate( + ArrayUtil.convertToWrapper( str.toCharArray() ), + new IteratingRunner<Character>() + { + public void run( Character arg ) + { + if (Character.isDigit( arg )) { + sb.append( arg ); + } + } } - } + ); + return sb.toString(); } @@ -104,12 +221,12 @@ public class StringUtil { return sb.toString(); } public static String asString(InputStream is) throws IOException{ - StringBuffer out = new StringBuffer(); - byte[] b = new byte[4096]; - - for (int n; (n = is.read(b)) != -1;) - out.append(new String(b,0,n)); - return out.toString(); + StringBuffer out = new StringBuffer(); + byte[] b = new byte[4096]; + + for (int n; (n = is.read(b)) != -1;) + out.append(new String(b,0,n)); + return out.toString(); } public static String removeEnd(String str, String remove) { @@ -122,7 +239,886 @@ public class StringUtil { return str; } - public static boolean isEmpty(CharSequence cs) { - return cs == null || cs.length() == 0; + /** + * remove string in target string + * if target is empty or remove word is empty then just return target string + * + * @param str - target string + * @param remove - remove string + * @return removed target string + */ + public static String removeStart(String str, String remove) { + if (isEmpty(str) || isEmpty(remove) ) { + return str; + } + if (str.startsWith(remove)){ + return str.substring(remove.length()); + } + return str; + } + + /* Logging */ + /** + * </p> + * Append hexa value for <code>ch</code> to <code>buffer</code> + * + * Hexa value must be two digit. Pad 0 if hexa value has 1 digit. + * </p> + * + * @param buffer {@link StringBuilder} to write + * @param ch decimal integer + */ + public static + void + appendHexa( + final StringBuilder buffer, + final int ch + ) + { + if ( ch < 16 ) + { + // if 1 digit containing hexadecimal + buffer.append( '0' ); + buffer.append( HEXA_CHARS[( 0x0f & ( ch ) )] ); + } + else + { + // if 2 digit containing hexadecimal + buffer.append( HEXA_CHARS[( 0x0f & ( ch >> 4 ) )] ); + buffer.append( HEXA_CHARS[( 0x0f & ( ch ) )] ); + } + } + + /** + * Add end seperation at logging line's end + * + * @param hexPart hex decimal part + * @param textPart text part + * @param ret all part + */ + protected static + void + lineEnd( + final StringBuilder hexPart, + final StringBuilder textPart, + final StringBuilder ret + ) + { + // append separator of area + hexPart.append( " |" ); + + // append separator of termination + textPart.append( "|\n" ); + + // concatencate two area + ret.append( hexPart ); + ret.append( textPart ); + + // clean each area + hexPart.delete( 0, hexPart.capacity() ); + textPart.delete( 0, textPart.capacity() ); + } + + /** + * <p> + * Convert <code>data</code> in hexadecimal format for logging or readibility + * + * Output layout<br> + * <table> + * <tr><td>Address( or offset )</td><td>byte character</td><td>hexadecimal</td></tr> + * </table> + * + * Replace control character to '.'<br> + * </p> + * + * <code> + * Logger logger = ... + * byte[] dump = ... + * logger.debug( StringUtil.text2hexa( dump ) ); + * </code> + * + * @param data byte array to convert + * + * @return converted textual string + * + * @see #text2hexa(byte[], int, int) + */ + public static + String + text2hexa( + final byte[] data + ) + { + if ( null == data ) + { + return NULL_STRING; + } + return text2hexa( data, 0, data.length ); + } + + /** + * <p> + * Convert data from <code>offset</code> to <code>offset</code> + <code>length</code> in hexadecimal format. + * + * Output layout<br> + * <table> + * <tr><td>Address( or offset )</td><td>byte character</td><td>hexadecimal</td></tr> + * </table> + * + * Replace control character to '.'<br> + * </p> + * + * @param data byte array to convert + * @param offset start position to convert + * @param length length to convert + * + * @return converted textual string + */ + public static + String + text2hexa( + final byte[] data, + final int offset, + final int length + ) + { + + if ( null == data ) + { + return NULL_STRING; + } + if ( data.length <= 0 ) + { + return EMPTY_BYTES_STRING; + } + + final ByteArrayInputStream reader = new ByteArrayInputStream( data, offset, length ); + final StringBuilder ret = new StringBuilder(); + final StringBuilder hexPart = new StringBuilder(); + final StringBuilder textPart = new StringBuilder(); + + int address = 0; + int ch = -1; + int printByte = 0; + int cnt = 0; + + // fill white space( ' ' ) in address title + hexPart.append( " " ); + + // make horizontal ruler + for ( int i = 0, n = WIDTH_PER_LINE / 4 ; i < n ; i++ ) + { + hexPart.append( "+-------" ); + textPart.append( "+---" ); + } + + lineEnd( hexPart, textPart, ret ); + + while ( 0 <= ( ch = reader.read() ) ) + { + if ( 0 == cnt ) + { + // calculate and print out start address + for ( int i = N_INT_BY_BYTE - 1 ; i >= 0 ; i-- ) + { + printByte = 0xFF & ( address >> ( 8 * i ) ); + appendHexa( hexPart, printByte ); + } + hexPart.append( " " ); + address += WIDTH_PER_LINE; + } + + appendHexa( hexPart, ch ); + if ( ( ch & 0x80 ) != 0 || ch < 32 ) + { // if ch is control character + // print out replaced character + textPart.append( CONTROL_CHARS_SHOWER ); + } + else + { + textPart.append( (char) ch ); + } + cnt++; + + if ( WIDTH_PER_LINE == cnt ) + { + lineEnd( hexPart, textPart, ret ); + cnt = 0; + } + } // END of while ( 0 <= (ch = reader.read() ) ) + + // fill white space( ' ' ) in remaining area + if ( 0 != cnt ) + { + for ( ; cnt < WIDTH_PER_LINE ; ++cnt ) + { + hexPart.append( " " ); + textPart.append( ' ' ); + } + lineEnd( hexPart, textPart, ret ); + } + + return ret.toString(); + } + + + /* Check & Verification */ + /** + * Check that <code>str</code> is <code>null</code> or empty string textually + * + * @param str string to check + * + * @return <code>true</code> if <code>str</code> is null or empty string or string containing only white space + * + * @see StringUtil#hasText( CharSequence ) + */ + public static + boolean + isEmpty( + final CharSequence str + ) + { + if ( null == str ) + { + return true; + } + + for ( int i=0, n=str.length() ; i<n ; ++i ) + { + if ( Character.isWhitespace( str.charAt( i ) ) ) + { + continue; + } + return false; + } + return true; + } + + /** + * Get length of string + * + * Return <code>0</code> if <code>str</code> is <code>null</code> + * + * @param str string whose length is checked + * + * @return length of <code>str</code> + */ + public static + int + size( + final CharSequence str + ) + { + if ( null == str ) + { + return 0; + } + return str.length(); + } + + /** + * <p> + * Check that <code>str</code> contain any character + * </p> + * @param str string to check + * + * @return <code>true</code> if <code>str</code> is not <code>null</code> nor empty string + * + * @see #size(CharSequence) + */ + public static + boolean + hasLength( + final CharSequence str + ) + { + return 0 < size( str ); + } + + /** + * Check that <code>str</code> has textual character + * + * @param str string to check + * + * @return <code>true</code> if <code>str</code> has textual character + * + * @see isEmpty( CharSequence ) + */ + public static + boolean + hasText( + final CharSequence str + ) + { + return !isEmpty( str ); + } + + /* Conversion */ + /** + * Check <code>strs</code> and return non-null string + * + * Return empty string if all of element in <code>strs</code> + * + * @param strs strings to check + * + * @return non-null in <code>strs</code> + * + * see #ObjectUtil{@link #nvl(String...)} + */ + public static + String + nvl( + final String... strs + ) + { + String val = ObjectUtil.nvl( strs ); + if ( null == val ) + { + return ""; + } + return val; + } + + /** + * Trim leading whitespaqce + * + * @param str string to trim + * + * @return trimmed string + */ + public static + String + trimLeading( + final String str + ) + { + if( !hasLength( str ) ) + { + return str; + } + + final char[] chs = str.toCharArray(); + for ( int i=0, n=chs.length ; i<n ; ++i ) + { + if ( !Character.isWhitespace( chs[i] ) ) + { + return new String( chs, i, str.length() - i ); + } + } + return EMPTY_STRING; + } + + /** + * Trim trailing white space + * + * @param str string to trim + * + * @return trimmed string + */ + public static + String + trimTrailing( + final String str + ) + { + if( !hasLength( str ) ) + { + return str; + } + + final char[] chs = str.toCharArray(); + for ( int i=chs.length-1, j=chs.length ; 0<j ; --i, --j ) + { + if ( !Character.isWhitespace( chs[i] ) ) + { + return new String( chs, 0, j ); + } + } + return EMPTY_STRING; + } + /** + * Remove white spaces at leading and trailing part of <code>str</code> + * + * Return empty string if <code>str</code> is <code>null</code> + * + * @param str string to convert + * + * @return converted string + * + * @see StringUtil#trimLeading(String) + * @see StringUtil#trimTrailing(String) + */ + public static + String + trim( + final String str + ) { + return trimTrailing( trimLeading( str ) ); + } + + /** + * Convert <code>str</code> to meaningful for search + * + * @param str string to convert + * + * @return converted string + */ + public static + String + getMeaningful( + final String str + ) { + if ( null == str ) + { + return EMPTY_STRING; + } + return trim( str ).toLowerCase(); + } + + /** + * Mask <code>str</code> with <code>maskingStr</code> + * + * Replace <code>str</code> to <code>maskingStr</code> with <code>str</code>'s length + * + * @param str string to mask + * @param maskingStr string to mask with + * + * @return masked string + */ + public static + String + mask( + final String str, + final String maskingStr + ) { + if ( null == str ) + { + return "null"; + } + + final StringBuilder buffer = new StringBuilder(); + for ( int i=0, n=str.length() ; i<n ; ++i ) + { + buffer.append( maskingStr ); + } + return buffer.toString(); + } + + /* Analysis & Extract */ + /** + * Extract <code>targetIndex</code> string from strings + * + * where <code>str</code> is splitted by <code>delimeter</code> + * + * @param str string with <code>delimeter</code> + * @param delimeter what split <code>str</code> with + * @param escaper escape character for <code>delimter</code> + * @param targetIndex index from fragments + * + * @return extracted string + */ + public static + String + getParamater( + final String str, + final char delimeter, + final int escaper, + final int targetIndex + ) + throws IOException + { + try + { + if ( null == str ) + { + return null; + } + final StringReader reader = new StringReader( str ); + StringWriter writer = null; + int ch = 0; + final int ST_NORMAL = 0; + final int ST_ESCAPE = 1; + int status = ST_NORMAL; + int index = 0; + if ( 0 == targetIndex ) + { + writer = new StringWriter(); + } + while ( 0 <= ( ch = reader.read() ) ) { + if ( ST_ESCAPE == status ) { + status = ST_NORMAL; + } else { + if ( escaper == ch ) { + status = ST_ESCAPE; + continue; + } else if ( delimeter == ch ) { + if ( index == targetIndex ) + { + return writer.toString(); + } + ++index; + if ( index == targetIndex ) + { + writer = new StringWriter(); + } + continue; + } + } + if ( null != writer ) + { + writer.write( (int) ch ); + } + } + if ( index == targetIndex ) + { + return writer.toString(); + } + return null; + } + catch ( final IOException e ) + { + // Never throw + throw new IllegalStateException( e ); + } + } + + /** + * Return substring starting <code>indexFromLast</code> from last + * + * @param str original string + * @param indexFromLast starting index from last + * + * @return substring + */ + public static + String + lastSubstring( + final String str, + final int indexFromLast + ) + { + if ( null == str ) + { + return null; + } + + final int length = str.length(); + + if ( length < indexFromLast ) + { + return str; + } + + return str.substring( length - indexFromLast ); + } + + /** + * Extract last fragment in strings split <code>str</code> with <code>separator</code> + * + * @param str origin string + * @param separator string for separation + * + * @return last fragment string + */ + public static + String + getLastSegment( + final String str, + final String separator + ) + { + if ( null == str ) + { + return EMPTY_STRING; + } + + final int index = str.lastIndexOf( separator ); + if ( index < 0 ) + { + return str; + } + + return str.substring( index + separator.length() ); + } + + /** + * Extract last fragment in string and return remaining string with <code>separator</code> + * + * @param str origin string + * @param separator string for separation + * + * @return remaining string + */ + public static + String + removeLastSegment( + final String str, + final String separator + ) + { + if ( null == str ) + { + return EMPTY_STRING; + } + + final int index = str.lastIndexOf( separator ); + + if ( index < 0 ) + { + return EMPTY_STRING; + } + + return str.substring( 0, index ); + + } + + /** + * Make <code>n</code> repeated <code>symbol</code> string + * + * @param symbol composing string + * @param n repeat count + * + * @return made string + */ + public static + String + multiply( + final String symbol, + final int n + ) + { + if ( null == symbol ) { + return EMPTY_STRING; + } + + final StringBuilder buffer = new StringBuilder(); + for ( int i=0 ; i<n ; ++i ) + { + buffer.append( symbol ); + } + return buffer.toString(); + } + + /** + * Check that <code>str</code> contain white spaces + * + * @param str string to check + * @return <code>true</code> if <code>str</code> contain white spaces + */ + public static + boolean + containsWhitespace( + final CharSequence str + ) + { + final int nChar = size( str ); + + for ( int i= 0; i< nChar; ++i ) + { + if ( Character.isWhitespace( str.charAt( i ) ) ) + { + return true; + } + } + return false; } + + + /** + * Trim leading <code>leadingCharacter</code> from <code>str</code> + * + * @param str string to trim + * @param leadingCharacter character to trim with + * + * @return trimmed string + */ + public static + String + trimLeadingCharacter( + final String str, + final char leadingCharacter + ) + { + if( !hasLength( str ) ) + { + return str; + } + + final char[] chs = str.toCharArray(); + for ( int i=0, n=chs.length ; i<n ; ++i ) + { + if ( leadingCharacter != chs[i] ) + { + return new String( chs, i, str.length() - i ); + } + } + return EMPTY_STRING; + } + + /** + * Trim trailing <code>trailingCharacter</code> from <code>str</code> + * + * @param str string to trim + * @param trailingCharacter character to trim with + * + * @return trimmed string + */ + public static + String + trimTrailingCharacter( + final String str, + final char trailingCharacter + ) + { + if( !hasLength( str ) ) + { + return str; + } + + final char[] chs = str.toCharArray(); + for ( int i=chs.length-1, j=chs.length ; 0<j ; --i, --j ) + { + if ( trailingCharacter != chs[i] ) + { + return new String( chs, 0, j ); + } + } + return EMPTY_STRING; + } + + /** + * Trim <code>str</code> with <code>character</code> + * + * @param str string to trim + * @param character character to trim with + * + * @return trimmed string + */ + public static + String + trimCharacter( + final String str, + final char character + ) + { + return trimTrailingCharacter( trimLeadingCharacter( str, character ), character ); + } + + /** + * Extract word at <coode>index</code> column in <code>doc</code> + * + * @param doc full string + * @param index column index + * + * @return word at <code>index</code> column + */ + public static + String + getWord( + final String doc, + final int index + ) + { + final StringBuilder buffer = new StringBuilder(); + + int position = index; + + if ( doc.length() < index ) + { + return ""; + } + + for ( int i = position - 1 ; 0 <= i ; --i ) + { + + int ch = doc.charAt( i ); + + if ( Character.isWhitespace( ch ) ) + { + break; + } + buffer.append( (char) ch ); + } + buffer.reverse(); + + for ( int i = position , n = doc.length() ; i < n ; ++i ) + { + int ch = doc.charAt( i ); + if ( Character.isWhitespace( ch ) ) + { + break; + } + buffer.append( (char) ch ); + } + + return buffer.toString(); + } + + /** + * Extract word in front of <coode>index</code> column in <code>doc</code> + * + * @param doc full string + * @param index column index + * + * @return word in front of <code>index</code> column + */ + public static + String + getPreviousWord( + final String doc, + final int index + ) + { + final StringBuilder buffer = new StringBuilder(); + + if ( index < 0 || doc.length() < index ) + { + Logger.debug( "Index[{0}] is out of bound :[0:{1}]", index, doc.length() ); + return ""; + } + + int ch = 0; + boolean bNeedWord = false; + if ( index < doc.length() ) + { + ch = doc.charAt( index ); + bNeedWord = Character.isWhitespace( ch ); + } + Logger.debug( "Character at index :'{0}'", (char ) ch ); + for ( int i = index - 1 ; 0 <= i ; --i ) + { + ch = doc.charAt( i ); + + if ( Character.isWhitespace( ch ) ) + { + if ( bNeedWord ) + { + continue; + } + Logger.debug( "Meet space at column {0}", i ); + break; + } + bNeedWord = false; + buffer.append( (char) ch ); + } + + return buffer.reverse().toString(); + } + + /** + * Enum to String array + * + * @param values enum values + * + * @return string array + */ + public static <T extends Enum<T>> String[] enumNameToStringArray(T[] values) { + int i = 0; + String[] result = new String[values.length]; + for (T value: values) { + result[i++] = value.name(); + } + return result; + } + } diff --git a/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java b/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java new file mode 100644 index 000000000..d51eed74a --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java @@ -0,0 +1,60 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util; + +/** + * ThreadUtil. + * + * Helper related to <code>Thread</code> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +ThreadUtil +{ + protected ThreadUtil() {} + + /** + * try to invoke {@link Thread#sleep(long)} in safe + * + * handle <code>milliseconds</code> to zero( 0 ) if it is negative + * + * @param milliseconds time to sleep in milliseconds + * + * @see Thread#sleep(long) + */ + public static void trySleep( final long milliseconds ) + { + if ( milliseconds <=0 ) + { + return ; + } + try { + Thread.sleep( milliseconds ); + } catch ( InterruptedException e ) { + } + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java b/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java new file mode 100644 index 000000000..3f2de9370 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java @@ -0,0 +1,94 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * Changhyun Lee <changhyun1.lee@samsung.com> + * Hyeongseok Heo <hyeongseok.heo@samsung.com> + * BonYong Lee <bonyong.lee@samsung.com> + * Kangho Kim <kh5325.kim@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ + +package org.tizen.common.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * ValidationUtil. + * + * Verification Using a regular expression. + * + * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core) + */ +public class ValidationUtil { + + /** + * Check for Email address. RFC 2822 (simplified)Matches a normal email address. Does not check the top-level domain. + * + * @param value email string + * + * @return if value is valied email + */ + public static boolean checkForEmail(String value) { + String regex = "[A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])??"; //$NON-NLS-1$ + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(value); + + return matcher.matches(); + } + + /** + * Check for URL string. + * + * @param value url string + * + * @return if value is valied url + */ + public static boolean checkForURL(String value) { + String regex = "\\b(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; //$NON-NLS-1$ + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(value); + + return matcher.matches(); + } + + /** + * Check for File extension. + * + * @param value file name + * @param extensions valied file extensions + * + * @return if value is valied file + */ + public static boolean checkForFileExtension(String value, String[] extensions) { + if (StringUtil.isEmpty(value) || extensions == null) { + return false; + } + + for (String ext : extensions) { + if (value.endsWith(ext)) { + return true; + } + } + return false; + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/ViewUtil.java b/org.tizen.common/src/org/tizen/common/util/ViewUtil.java index 05a3ae525..1bb30fb35 100644 --- a/org.tizen.common/src/org/tizen/common/util/ViewUtil.java +++ b/org.tizen.common/src/org/tizen/common/util/ViewUtil.java @@ -25,7 +25,6 @@ package org.tizen.common.util; import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; @@ -41,9 +40,9 @@ public class ViewUtil { ViewRunnable runnable = new ViewRunnable(id); if (sync) { - Display.getDefault().syncExec(runnable); + SWTUtil.syncExec( runnable ); } else { - Display.getDefault().asyncExec(runnable); + SWTUtil.asyncExec( runnable ); } } @@ -94,15 +93,17 @@ public class ViewUtil { } public static IWorkbenchWindow getWorkbenchWindow() { - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - if (window == null) { - if (workbench.getWorkbenchWindowCount() == 1) { - window = workbench.getWorkbenchWindows()[0]; - } + final IWorkbench workbench = PlatformUI.getWorkbench(); + final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + if ( window != null ) + { + return window; } - - return window; + if ( workbench.getWorkbenchWindowCount() == 0 ) + { + return null; + } + return workbench.getWorkbenchWindows()[0]; } -}
\ No newline at end of file +} diff --git a/org.tizen.common/src/org/tizen/common/cache/ColorCache.java b/org.tizen.common/src/org/tizen/common/util/cache/ColorCache.java index fbd1a3659..3704dc5ec 100644 --- a/org.tizen.common/src/org/tizen/common/cache/ColorCache.java +++ b/org.tizen.common/src/org/tizen/common/util/cache/ColorCache.java @@ -23,15 +23,15 @@ * - S-Core Co., Ltd
*
*/
-package org.tizen.common.cache;
+package org.tizen.common.util.cache;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.SWTUtil;
/**
* Class for caching colors
@@ -41,33 +41,20 @@ import org.eclipse.swt.widgets.Display; */
public final class ColorCache {
- public static final RGB BLACK = new RGB(0, 0, 0);
- public static final RGB WHITE = new RGB(255, 255, 255);
+ public static final RGB BLACK = new RGB(0, 0, 0);
+ public static final RGB WHITE = new RGB(255, 255, 255);
- private static Map<RGB, Color> _colorTable;
- private static ColorCache _instance;
-
- static {
- _colorTable = new HashMap<RGB, Color>();
- new ColorCache();
- }
+ private static Map<RGB, Color> _colorTable = new HashMap<RGB, Color>();
private ColorCache() {
- _instance = this;
- }
-
- public static ColorCache getInstance() {
- return _instance;
}
/**
* Disposes of all colors. DO ONLY CALL THIS WHEN YOU ARE SHUTTING DOWN YOUR
* APPLICATION!
*/
- public static void disposeColors() {
- Iterator<Color> e = _colorTable.values().iterator();
- while (e.hasNext())
- e.next().dispose();
+ synchronized public static void disposeColors() {
+ SWTUtil.tryDispose( _colorTable.values().toArray( new Widget[0]) );
_colorTable.clear();
}
@@ -80,27 +67,27 @@ public final class ColorCache { return getColorFromRGB(new RGB(0, 0, 0));
}
- public static Color getColorFromRGB(RGB rgb) {
+ synchronized public static Color getColorFromRGB(RGB rgb) {
Color color = _colorTable.get(rgb);
if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
+ color = new Color( SWTUtil.getDisplay(), rgb);
_colorTable.put(rgb, color);
}
return color;
}
- public static Color getColor(int r, int g, int b) {
+ synchronized public static Color getColor(int r, int g, int b) {
RGB rgb = new RGB(r, g, b);
Color color = _colorTable.get(rgb);
if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
+ color = new Color( SWTUtil.getDisplay(), rgb);
_colorTable.put(rgb, color);
}
return color;
}
-
-}
\ No newline at end of file +
+}
diff --git a/org.tizen.common/src/org/tizen/common/cache/FontCache.java b/org.tizen.common/src/org/tizen/common/util/cache/FontCache.java index ec5b81a51..5a83a7700 100644..100755 --- a/org.tizen.common/src/org/tizen/common/cache/FontCache.java +++ b/org.tizen.common/src/org/tizen/common/util/cache/FontCache.java @@ -23,14 +23,17 @@ * - S-Core Co., Ltd
*
*/
-package org.tizen.common.cache;
+package org.tizen.common.util.cache;
+
+import static org.tizen.common.util.SWTUtil.tryDispose;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.SWTUtil;
/**
* Caching class for fonts. Also deals with re-creating fonts should they have been disposed when the
@@ -47,12 +50,8 @@ public class FontCache { * Disposes all fonts and clears out the cache. Never call this unless you are shutting down your
* code/client/etc.
*/
- public static void disposeAll() {
- for (OneFont of : _existing) {
- if (of.getFont() != null && !of.getFont().isDisposed()) {
- of.getFont().dispose();
- }
- }
+ synchronized public static void disposeAll() {
+ SWTUtil.tryDispose( _existing.toArray( new Widget[0] ) );
_existing.clear();
}
@@ -63,7 +62,7 @@ public class FontCache { * @param fd FontData
* @return Font or null on error
*/
- public static Font getFont(FontData fd) {
+ synchronized public static Font getFont(FontData fd) {
try {
boolean disposed = false;
OneFont toRemove = null;
@@ -92,7 +91,7 @@ public class FontCache { return null;
}
- public static int getCount() {
+ synchronized public static int getCount() {
return _existing.size();
}
@@ -104,7 +103,10 @@ public class FontCache { */
public static Font getFont(Font font) {
try {
- if (font == null || font.isDisposed()) return null;
+ if (font == null || font.isDisposed())
+ {
+ return null;
+ }
FontData fd = font.getFontData()[0];
return getFont(fd);
@@ -124,7 +126,7 @@ public class FontCache { * @param style Style of font
* @return Font or null on error
*/
- public static Font getFont(String fontName, int height, int style) {
+ synchronized public static Font getFont(String fontName, int height, int style) {
try {
boolean disposed = false;
OneFont toRemove = null;
@@ -165,14 +167,14 @@ class OneFont { _name = name;
_height = height;
_style = style;
- _font = new Font(Display.getDefault(), name, height, style);
+ _font = new Font( SWTUtil.getDisplay(), name, height, style);
}
public OneFont(FontData fd) {
_name = fd.getName();
_height = fd.getHeight();
_style = fd.getStyle();
- _font = new Font(Display.getDefault(), fd);
+ _font = new Font( SWTUtil.getDisplay(), fd);
}
public String getName() {
diff --git a/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java b/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java new file mode 100644 index 000000000..778991931 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java @@ -0,0 +1,108 @@ +/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.cache;
+
+import java.io.InputStream;
+import java.util.HashMap;
+
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.IOUtil;
+import org.tizen.common.util.SWTUtil;
+
+/**
+ * Class for caching images
+ *
+ * @author Emil
+ */
+public class ImageCache {
+
+ // what path to get to the "icons" directory without actually including it
+ private static final String ICON_ROOT_PATH = "icons/";
+
+ private final static HashMap<String, Image> _ImageMap = new HashMap<String, Image>();
+
+ /**
+ * Returns an image that is also cached if it has to be created and does not already exist in the cache.
+ *
+ * @param fileName Filename of image to fetch
+ * @return Image null if it could not be found
+ */
+ public static Image getImage(String fileName) {
+ fileName = ICON_ROOT_PATH + fileName;
+ Image image = _ImageMap.get(fileName);
+ if (image == null) {
+ image = createImage(fileName);
+ _ImageMap.put(fileName, image);
+ }
+ return image;
+ }
+
+ /**
+ * creates the image, and tries really hard to do so
+ *
+ * FIXME : substring is not exact expression to remove leading '/'
+ *
+ * @param fileName image file name
+ *
+ * @return loaded <code>Image</code>
+ */
+ synchronized private static Image createImage(String fileName) {
+ ClassLoader classLoader = ImageCache.class.getClassLoader();
+ InputStream is = classLoader.getResourceAsStream(fileName);
+ try
+ {
+ if (is == null) {
+ // the old way didn't have leading slash, so if we can't find the image stream,
+ // let's see if the old way works.
+ is = classLoader.getResourceAsStream(fileName.substring(1));
+ }
+ if (is == null) {
+ is = classLoader.getResourceAsStream(fileName);
+ if (is == null) {
+ is = classLoader.getResourceAsStream(fileName.substring(1));
+ if (is == null) { return null; }
+ }
+ }
+
+ return new Image( SWTUtil.getDisplay(), is);
+ }
+ finally
+ {
+ IOUtil.tryClose( is );
+ }
+ }
+
+ /**
+ * Disposes ALL images that have been cached.
+ */
+ synchronized public static void dispose() {
+
+ SWTUtil.tryDispose( _ImageMap.values().toArray( new Widget[0]) );
+ _ImageMap.clear();
+
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/manager/ColorCache.java b/org.tizen.common/src/org/tizen/common/util/cache/NamedColorCache.java index 3920db1d1..08203df15 100644 --- a/org.tizen.common/src/org/tizen/common/manager/ColorCache.java +++ b/org.tizen.common/src/org/tizen/common/util/cache/NamedColorCache.java @@ -22,19 +22,19 @@ * - S-Core Co., Ltd * */ -package org.tizen.common.manager; +package org.tizen.common.util.cache; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; +import org.tizen.common.util.Assert; +import org.tizen.common.util.SWTUtil; -public class ColorCache { +public class NamedColorCache { private String[] keys; private Color[] colors; - public ColorCache(String[] keys){ - if(keys==null||keys.length==0) - throw new IllegalArgumentException(Messages.ColorCache_0); + public NamedColorCache(String[] keys){ + Assert.notEmpty( keys, "Argument must not be null" ); this.keys = keys; this.colors = new Color[keys.length]; @@ -71,7 +71,7 @@ public class ColorCache { color=null; } - colors[index] = new Color(Display.getCurrent(),rgb); + colors[index] = new Color( SWTUtil.getDisplay(), rgb ); } public void dispose(){ diff --git a/org.tizen.common/src/org/tizen/common/util/io/Buffer.java b/org.tizen.common/src/org/tizen/common/util/io/Buffer.java new file mode 100644 index 000000000..888d346c7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/io/Buffer.java @@ -0,0 +1,504 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util.io; + +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.LinkedList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p> + * Buffer. + * + * Buffer for high performance input / output + * + * No synchronized and no retention + * + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +Buffer +implements Closeable +{ + + /** + * Logger for this instance + */ + protected Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Pool for {@link ByteBuffer} + * @see BufferPool + */ + protected BufferPool pool; + + /** + * Used buffers + */ + protected LinkedList<ByteBuffer> useds = new LinkedList<ByteBuffer>(); + + /** + * in-using read buffer + */ + protected ByteBuffer readBuffer; + + /** + * in-using write buffer + */ + protected ByteBuffer writeBuffer; + + + /** + * in-using buffer + */ + protected LinkedList<ByteBuffer> usings = new LinkedList<ByteBuffer>(); + + /** + * bytes to be read + */ + protected int nReaded = 0; + + /** + * total buffer size + */ + protected int size = 0; + + /** + * buffer index + */ + protected int index; + + /** + * Constructor with {@link BufferPool} + * + * @param pool {@link BufferPool} + */ + public + Buffer( + final BufferPool pool + ) + { + this.pool = pool; + } + + /** + * <p> + * Return contents' size in buffer + * </p> + * + * @return contents' size + */ + public + int + size() + { + return this.size; + } + + /** + * <p> + * Return the number of buffer + * </p> + * @return the number of {@link ByteBuffer} + */ + public + int + getBufferSize() + { + return useds.size() + usings.size() + ( ( null == readBuffer )?0:1 ) + ( ( null == writeBuffer )?0:1 ); + } + + /** + * Return in-using {@link ByteBuffer} for writing + * + * @return in-using buffer + * + * @throws IOException When new buffer can't be created + */ + public + ByteBuffer + getBufferForWrite() + throws IOException + { + if ( null == writeBuffer ) + { + writeBuffer = pool.borrow(); + } + else if ( writeBuffer.remaining() <= 0 ) + { + writeBuffer.flip(); + usings.addLast( writeBuffer ); + writeBuffer = pool.borrow(); + } + + return writeBuffer; + } + + /** + * Return in-using {@link ByteBuffer} for reading + * + * @return in-using buffer + * + * @throws IOException reserved + */ + public + ByteBuffer + getBufferForRead() + throws IOException + { + if ( null != readBuffer && 0 == readBuffer.remaining() ) + { + readBuffer.position( 0 ); + useds.add( readBuffer ); + readBuffer = null; + } + + if ( null == readBuffer ) + { + if ( usings.isEmpty() ) + { + if ( null != writeBuffer ) + { + readBuffer = writeBuffer; + readBuffer.flip(); + writeBuffer = null; + } + else + { + return null; + } + } + else + { + readBuffer = usings.removeFirst(); + } + } + + return readBuffer; + } + + /** + * Read bytes from <code>channel</code> + * + * @param channel {@link SocketChannel} + * + * @return the number character to read + * + * @throws IOException When buffer is NOT available + */ + public + int + readFrom( + final SocketChannel channel + ) + throws IOException + { + int sum = 0; + int nCnt = 0; + while ( true ) + { + final ByteBuffer buffer = getBufferForWrite(); + int nRead = channel.read( buffer ); + if ( nRead < 0 ) + { + throw new EOFException(); + } + else if ( 0 == nRead ) + { + this.size += sum; + if ( 0 < sum ) + { + logger.info( "{} bytes[{}] read from {}", new Object[] { sum, nCnt, channel } ); + } + return sum; + } + sum += nRead; + ++nCnt; + } + } + + + /** + * Write all contents to <code>channel</code> + * + * @param channel {@link SocketChannel} + * + * @return the number of bytes to write + * + * @throws IOException When buffer is NOT available + */ + public + int + writeTo( + final SocketChannel channel + ) throws IOException + { + int sum = 0; + + while ( 0 < size ) + { + final ByteBuffer buffer = getBufferForRead(); + final int nWrite = channel.write( buffer ); + if ( 0 < nWrite ) + { + this.size -= nWrite; + sum += nWrite; + } + } + + nReaded += sum; + + logger.info( "Send {} bytes to {}", sum, channel ); + + return sum; + } + + /** + * Read and return a byte character from buffer + * + * @return character to read + * + * @throws IOException When buffer is NOT available + */ + public + int + read() + throws IOException + { + final ByteBuffer buffer = getBufferForRead(); + if ( null == buffer ) + { + return -1; + } + + int ch = (int) ( 0xFF & buffer.get() ); + --size; + ++nReaded; + + return ch; + } + + /** + * Read integer from buffer + * + * @return integer to read + * + * @throws IOException When buffer is NOT available + */ + public + int + readInt() throws IOException + { + int i1 = read(); + int i2 = read(); + int i3 = read(); + int i4 = read(); + + return ( (int) 0xFF & i1 ) << 24 | ( (int) 0xFF & i2 ) << 16 | ( (int) 0xFF & i3 ) << 8 | ( (int) 0xFF & i4 ); + } + + /** + * Write a byte character to buffer + * + * @param value character to write + * + * @throws IOException When buffer is NOT available + */ + public + void + write( final int value ) throws IOException + { + final ByteBuffer buffer = getBufferForWrite(); + buffer.put( (byte) value ); + ++size; + } + + /** + * Write <code>bytes</code> to buffer + * + * @param bytes contents to write + * + * @throws IOException When buffer is NOT available + */ + public + void + write( final byte[] bytes ) throws IOException + { + for ( int i = 0, n = bytes.length ; i < n ; ) + { + final ByteBuffer buffer = getBufferForWrite(); + final int remaingSize = buffer.remaining(); + buffer.put( bytes, i, remaingSize ); + i += remaingSize; + } + } + + /** + * Write integer to buffer + * + * @param value integer to write + * + * @throws IOException When buffer is NOT available + */ + public + void + writeInt( + final int value + ) + throws IOException + { + write( 0xFF & ( value >> 24 ) ); + write( 0xFF & ( value >> 16 ) ); + write( 0xFF & ( value >> 8 ) ); + write( 0xFF & ( value ) ); + } + + /** + * Reset using resource( buffer, index, ...etc ) + */ + public + void + reset() + { + if ( null != readBuffer ) + { + readBuffer.position(); + useds.add( readBuffer ); + } + + useds.addAll( usings ); + + if ( null != writeBuffer ) + { + writeBuffer.flip(); + useds.add( writeBuffer ); + writeBuffer = null; + } + + usings = useds; + useds = new LinkedList<ByteBuffer>(); + size += nReaded; + nReaded = 0; + } + + /** + * Pack unused resource + * + * @throws IOException When {@link ByteBuffer} can't be release + */ + synchronized public + void + pack() throws IOException + { + for ( final ByteBuffer buffer : useds ) + { + nReaded -= buffer.remaining(); + pool.release( buffer ); + } + + useds.clear(); + } + + /* (non-Javadoc) + * @see java.io.Closeable#close() + */ + synchronized public + void + close() + throws IOException + { + if ( null != readBuffer ) + { + pool.release( readBuffer ); + readBuffer = null; + } + for ( final ByteBuffer buffer : usings ) + { + pool.release( buffer ); + } + usings.clear(); + if ( null != writeBuffer ) + { + pool.release( writeBuffer ); + writeBuffer = null; + } + + for ( final ByteBuffer buffer : useds ) + { + pool.release( buffer ); + } + + useds.clear(); + } + + /** + * Concatencate buffers + * + * @param buffers {@link Buffer}s to concatenate + * + * @return {@link Buffer} to be concatenate + */ + public static + Buffer + concatenate( + final Buffer... buffers + ) + { + final Buffer ret = new Buffer( null ); + boolean bInit = false; + for ( final Buffer buffer : buffers ) + { + if ( bInit && ret.pool != buffer.pool ) + { + throw new IllegalArgumentException( "Unmatching buffer pool" ); + } + ret.pool = buffer.pool; + bInit = true; + + buffer.reset(); + ret.usings.addAll( buffer.usings ); + ret.size += buffer.size; + } + + return ret; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() + { + return "Buffer[" + size + "]"; + } +} + diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java b/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java new file mode 100644 index 000000000..32608a9a6 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java @@ -0,0 +1,81 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; + +/** + * <p> + * BufferInputStream. + * + * {@link InputStream} to use {@link Buffer} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see Buffer + */ +public class +BufferInputStream +extends InputStream +{ + /** + * buffer to store bytes + */ + protected final Buffer buffer; + + /** + * Constructor with buffer + * + * @param buffer {@link ByteBuffer} + */ + public + BufferInputStream( + final Buffer buffer + ) + { + if ( null == buffer ) + { + throw new NullPointerException(); + } + + this.buffer = buffer; + } + + /* (non-Javadoc) + * @see java.io.InputStream#read() + */ + @Override + public + int + read() + throws IOException + { + return buffer.read(); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java b/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java new file mode 100644 index 000000000..3a4a195ae --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java @@ -0,0 +1,94 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; + +/** + * <p> + * BufferOutputStream. + * + * {@link OutputStream} to use {@link Buffer} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see Buffer + */ +public class +BufferOutputStream +extends OutputStream +{ + /** + * buffer to store bytes + */ + protected Buffer buffer; + + /** + * Constructor with buffer + * + * @param buffer {@link ByteBuffer} + */ + public + BufferOutputStream( + final Buffer buffer + ) + { + if ( null == buffer ) + { + throw new NullPointerException(); + } + this.buffer = buffer; + } + + /** + * Return internal buffer + * + * @return {@link Buffer} + */ + public + Buffer + getBuffer() + { + return this.buffer; + } + + /* (non-Javadoc) + * @see java.io.OutputStream#write(int) + */ + @Override + public + void + write( + final int b + ) + throws IOException + { + buffer.write( b ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java b/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java new file mode 100644 index 000000000..ee6d938b7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java @@ -0,0 +1,248 @@ +/* + * Common + * + * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + * + * Contact: + * BonYong Lee <bonyong.lee@samsung.com> + * + * 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. + * + * Contributors: + * - S-Core Co., Ltd + * + */ +package org.tizen.common.util.io; + +import java.io.Closeable; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.LinkedList; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.pool.BasePoolableObjectFactory; +import org.apache.commons.pool.ObjectPool; +import org.apache.commons.pool.impl.GenericObjectPoolFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <p> + * BufferPool. + * + * Pool for {@link Buffer} + * </p> + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + */ +public class +BufferPool +implements Closeable +{ + + /** + * The default number of buffer fragments + */ + protected static final int N_CREATION = 1024; + + /** + * Buffer fragment's default size + */ + protected static final int BUFFER_SIZE = 256; + + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * The number of buffer fragements to create + */ + protected int nCreation = N_CREATION; + + /** + * Buffer fragement's size + */ + protected int bufferSize = BUFFER_SIZE; + + /** + * Set the number of fragment + * + * @param nCreation the number of fragment + */ + public + void + setNumberOfFragments( + final int nCreation + ) + { + this.nCreation = nCreation; + } + + /** + * Set buffer fragment's size + * @param bufferSize buffer fargement's size + */ + public + void + setSizeOfFragment( + final int bufferSize + ) + { + this.bufferSize = bufferSize; + } + + /** + * Pool for {@link ByteBuffer} + */ + protected final ObjectPool<ByteBuffer> bufferPool = + new GenericObjectPoolFactory<ByteBuffer>( new BasePoolableObjectFactory<ByteBuffer>() { + + protected final LinkedList<ByteBuffer> buffers = new LinkedList<ByteBuffer>(); + + /* (non-Javadoc) + * @see org.apache.commons.pool.BasePoolableObjectFactory#makeObject() + */ + @Override + public + ByteBuffer + makeObject() + throws Exception + { + logger.trace( "{} buffer(s) exist", buffers.size() ); + if ( !buffers.isEmpty() ) + { + return buffers.removeFirst(); + } + + final long startTime = System.currentTimeMillis(); + final int totalSize = nCreation * bufferSize; + + final ByteBuffer totalBuffer = ByteBuffer.allocateDirect( totalSize ); + + for ( int limit = bufferSize ; limit <= totalSize ; limit += bufferSize ) + { + totalBuffer.limit( limit ); + buffers.add( totalBuffer.slice() ); + totalBuffer.position( limit ); + } + + final long endTime = System.currentTimeMillis(); + logger.info( "Buffer creation time :{} ms", ( endTime - startTime ) ); + + return buffers.removeFirst(); + } + + + /* (non-Javadoc) + * @see org.apache.commons.pool.BasePoolableObjectFactory#activateObject(java.lang.Object) + */ + public + void + activateObject( + final ByteBuffer buffer + ) + throws Exception + { + super.activateObject( buffer ); + + buffer.clear(); + } + + }, -1 ).createPool(); + + /** + * Pick-up and return {@link ByteBuffer} from pool + * + * @return {@link ByteBuffer} + * + * @throws IOException When {@link ByteBuffer} can't be created or available + */ + public + ByteBuffer + borrow() + throws IOException + { + try + { + return bufferPool.borrowObject(); + } + catch ( + final Exception e + ) + { + throw new IOException( e ); + } + } + + /** + * Release buffer to pool + * + * @param buffer {@link ByteBuffer} to release + * + * @throws IOException When {@link ByteBuffer} can't be release + */ + public + void + release( + final ByteBuffer buffer + ) throws IOException + { + try + { + bufferPool.returnObject( buffer ); + } + catch + ( + final Exception e + ) + { + throw new IOException( e ); + } + } + + /* (non-Javadoc) + * @see java.io.Closeable#close() + */ + @Override + public + void + close() + throws IOException + { + + try { + bufferPool.close(); + } catch ( + final Exception e + ) + { + throw new IOException( e ); + } + + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public + String + toString() + { + return ObjectUtils.toString( this ); + } + + +} diff --git a/org.tizen.common/src/org/tizen/common/log/Logger.java b/org.tizen.common/src/org/tizen/common/util/log/Logger.java index 6f09f7824..59d172173 100644 --- a/org.tizen.common/src/org/tizen/common/log/Logger.java +++ b/org.tizen.common/src/org/tizen/common/util/log/Logger.java @@ -23,7 +23,7 @@ * */ -package org.tizen.common.log; +package org.tizen.common.util.log; import java.text.MessageFormat; @@ -31,7 +31,7 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.tizen.common.CommonPlugin; -import org.tizen.common.console.ConsoleManager; +import org.tizen.common.ui.view.console.ConsoleManager; /** @@ -74,6 +74,11 @@ public class Logger { log(new Status(IStatus.ERROR, getCallerName(), e.toString(), e)); } } + + public static void debug( String message, Object... arguments ) + { + + } public static void info(String message, Object... arguments) { log(new Status(Status.INFO, getCallerName(), getPossiblyFormattedString(message, arguments))); diff --git a/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java new file mode 100644 index 000000000..55b015f8b --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java @@ -0,0 +1,181 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.classpath; + +import static org.tizen.common.util.StringUtil.removeLastSegment; +import static org.tizen.common.util.StringUtil.trimLeadingCharacter; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Collection; +import java.util.LinkedHashSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.util.Assert; + +/** + * Connection. + * + * {@link URLConnection} for classpath url + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +Connection +extends URLConnection +{ + + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + protected String fqcn; + + protected URL internalUrl = null; + + /** + * <p> + * Constructor with classpath url + * </p> + * + * @param url url for resouce in classpath + */ + protected Connection( final URL url, final String fqcn ) + { + super( url ); + + this.fqcn = fqcn; + logger.debug( "Fully qualified class name :{}", fqcn ); + } + + /* (non-Javadoc) + * @see java.net.URLConnection#connect() + */ + @Override + public + void + connect() + throws IOException + { + Assert.isNull( this.internalUrl ); + + final String path = trimLeadingCharacter( getURL().getPath(), '/' ); + + final Collection<ClassLoader> classLoaders = getClassLoaders(); + logger.trace( "Classloaders :{}", classLoaders ); + + for ( final ClassLoader cl : classLoaders ) + { + URL url = cl.getResource( path ); + logger.trace( "Check url for {} :{}", path, url ); + if ( null == url ) + { + continue; + } + + this.internalUrl = url; + connected = true; + return ; + } + + if ( null == fqcn ) + { + connected = true; + return ; + } + + final String packageName = removeLastSegment( fqcn, "." ); + final String fullPath = trimLeadingCharacter( packageName.replace( '.', '/' ), '/' ) + "/" + path; + logger.trace( "Package name :{}, Full path :{}", packageName, fullPath ); + + for ( final ClassLoader cl : classLoaders ) + { + URL url = cl.getResource( fullPath ); + logger.trace( "Check url for {} :{}", fullPath, url ); + if ( null == url ) + { + continue; + } + + this.internalUrl = url; + connected = true; + return ; + } + + } + + /** + * <p> + * Return classloaders to provide resource<br> + * + * ClassLoader is following + * <ul> + * <li>Context ClassLoader</li> + * <li>ClassLoader for this class</li> + * <li>SystemClassLoader</li> + * </ul> + * </p> + * + * @return {@link ClassLoader} candidate + */ + protected static Collection<ClassLoader> getClassLoaders() + { + final LinkedHashSet<ClassLoader> classLoaders = new LinkedHashSet<ClassLoader>(); + + if ( null != Thread.currentThread().getContextClassLoader() ) + { + classLoaders.add( Thread.currentThread().getContextClassLoader() ); + } + + classLoaders.add( Connection.class.getClassLoader() ); + classLoaders.add( ClassLoader.getSystemClassLoader() ); + + return classLoaders; + } + + /* (non-Javadoc) + * @see java.net.URLConnection#getInputStream() + */ + @Override + public + InputStream + getInputStream() + throws IOException + { + if ( !connected ) + { + connect(); + } + if ( null == this.internalUrl ) + { + throw new IOException( "resource not found" ); + } + logger.trace( "Open stream :{}", internalUrl ); + + return internalUrl.openStream(); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java new file mode 100644 index 000000000..b87d5aee7 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java @@ -0,0 +1,104 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.classpath; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.util.ObjectUtil; + +/** + * Handler. + * + * {@link URLStreamHandler} for classpath url + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +Handler +extends URLStreamHandler +{ + + + /** + * Logger of object + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Full qualified class name of caller( exactly caller that call new URL() ) + */ + protected final String fqcnOfCaller; + + public Handler() + { + fqcnOfCaller = pickupCaller(); + } + + protected String pickupCaller() + { + final StackTraceElement[] callStacks = new Exception().getStackTrace(); + + boolean bUrl = false; + + for ( final StackTraceElement element : callStacks ) + { + logger.trace( "Check stack :{}", element ); + final String className = element.getClassName(); + logger.trace( "Class :{}", className ); + + if ( ObjectUtil.equals( className, URL.class.getName() ) ) + { + bUrl = true; + } + else if ( bUrl ) + { + return className; + } + } + + return null; + } + + + /* (non-Javadoc) + * @see java.net.URLStreamHandler#openConnection(java.net.URL) + */ + @Override + protected + URLConnection + openConnection( + final URL u + ) + throws IOException + { + return new Connection( u, fqcnOfCaller ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java new file mode 100644 index 000000000..7c13ac232 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java @@ -0,0 +1,54 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.cp; + +import java.net.URL; +import java.net.URLConnection; + +/** + * Connection. + * + * {@link URLConnection} for classpath url + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see org.tizen.common.util.url.classpath.Connection + */ +public class +Connection +extends org.tizen.common.util.url.classpath.Connection +{ + + /** + * Constructor with url + * + * @param url {@link URL} + */ + protected Connection( final URL url, final String fqcn ) + { + super( url, fqcn ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java new file mode 100644 index 000000000..d2f9686b9 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java @@ -0,0 +1,60 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.cp; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; + +/** + * Handler. + * + * {@link URLStreamHandler} for classpath url + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see org.tizen.common.util.url.classpath.Handler + */ +public class +Handler +extends org.tizen.common.util.url.classpath.Handler +{ + + /* (non-Javadoc) + * @see java.net.URLStreamHandler#openConnection(java.net.URL) + */ + @Override + protected + URLConnection + openConnection( + final URL u + ) + throws IOException + { + return new Connection( u, fqcnOfCaller ); + } + +} diff --git a/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java new file mode 100644 index 000000000..e32f42da2 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java @@ -0,0 +1,125 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.vf; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.tizen.common.file.VirtualFileHandler; + +/** + * Connection. + * + * {@link URLConnection} for {@link VirtualFileHandler} + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + */ +public class +Connection +extends URLConnection +{ + + /** + * Virutal file handler to search + */ + protected static VirtualFileHandler vfHandler = new VirtualFileHandler(); + + /** + * Logger for this instance + */ + protected final Logger logger = LoggerFactory.getLogger( getClass() ); + + /** + * Return {@link VirtualFileHandler} to search + * + * @return {@link #vfHandler} + */ + public static + VirtualFileHandler + getVirtualFileHandler() + { + return vfHandler; + } + + /** + * Set {@link VirtualFileHandler} to search + * + * @param vfHandler new {@link VirtualFileHandler} + */ + public static + void + setVirtualFileHandler( + final VirtualFileHandler vfHandler + ) + { + Connection.vfHandler = vfHandler; + } + + + + + /** + * Constructor with url + * + * @param url {@link URL} + */ + protected + Connection( + final URL url + ) + { + super( url ); + logger.trace( "URL :{}", url ); + } + + /* (non-Javadoc) + * @see java.net.URLConnection#connect() + */ + @Override + public + void + connect() + throws IOException + { + logger.trace( "connect" ); + } + + /* (non-Javadoc) + * @see java.net.URLConnection#getInputStream() + */ + public + InputStream + getInputStream() + throws IOException + { + final String path = url.getPath(); + logger.trace( "Path :{}", path ); + return vfHandler.read( path ); + } +} diff --git a/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java new file mode 100644 index 000000000..95089ff68 --- /dev/null +++ b/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java @@ -0,0 +1,59 @@ +/* +* Common +* +* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. +* +* Contact: +* BonYong Lee <bonyong.lee@samsung.com> +* +* 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. +* +* Contributors: +* - S-Core Co., Ltd +* +*/ +package org.tizen.common.util.url.vf; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; + +/** + * Handler. + * + * {@link URLStreamHandler} for classpath url + * + * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core) + * + * @see org.tizen.common.util.url.classpath.Handler + */ +public class +Handler +extends URLStreamHandler +{ + /* (non-Javadoc) + * @see java.net.URLStreamHandler#openConnection(java.net.URL) + */ + @Override + protected + URLConnection + openConnection( + final URL u + ) + throws IOException + { + return new Connection( u ); + } + +} |