Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 356a75dd769ebcaddd7d432e49ff7ab8cda7e032 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*******************************************************************************
 * Copyright (c) 2012, 2015 Wind River Systems, Inc. and others. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Wind River Systems          - initial API and implementation
 * Anna Dushistova (MontaVista)- adapted from org.eclipse.tcf.te.tcf.launch.core.steps.LaunchProcessStep
 *******************************************************************************/

package org.eclipse.tcf.te.tcf.launch.cdt.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.osgi.util.NLS;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IFileSystem;
import org.eclipse.tcf.te.core.utils.text.StringUtil;
import org.eclipse.tcf.te.runtime.callback.Callback;
import org.eclipse.tcf.te.runtime.concurrent.util.ExecutorsUtil;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer;
import org.eclipse.tcf.te.runtime.properties.PropertiesContainer;
import org.eclipse.tcf.te.runtime.services.filetransfer.FileTransferItem;
import org.eclipse.tcf.te.runtime.services.interfaces.filetransfer.IFileTransferItem;
import org.eclipse.tcf.te.runtime.utils.Host;
import org.eclipse.tcf.te.runtime.utils.net.IPAddressUtil;
import org.eclipse.tcf.te.tcf.core.interfaces.ITransportTypes;
import org.eclipse.tcf.te.tcf.core.streams.StreamsDataReceiver;
import org.eclipse.tcf.te.tcf.core.streams.StreamsDataReceiver.Listener;
import org.eclipse.tcf.te.tcf.filesystem.core.services.FileTransferService;
import org.eclipse.tcf.te.tcf.launch.cdt.activator.Activator;
import org.eclipse.tcf.te.tcf.launch.cdt.interfaces.IRemoteTEConfigurationConstants;
import org.eclipse.tcf.te.tcf.launch.cdt.nls.Messages;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerNode;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.IPeerModelLookupService;
import org.eclipse.tcf.te.tcf.locator.model.ModelManager;
import org.eclipse.tcf.te.tcf.processes.core.interfaces.launcher.IProcessLauncher;
import org.eclipse.tcf.te.tcf.processes.core.launcher.ProcessLauncher;
import org.eclipse.tm.terminal.view.core.interfaces.constants.ILineSeparatorConstants;
import org.eclipse.tm.terminal.view.core.interfaces.constants.ITerminalsConnectorConstants;

public class TEHelper {

	public static void remoteFileTransfer(IPeer peer, String localFilePath, String remoteFilePath, SubProgressMonitor monitor) throws IOException {
		// Copy the host side file to a temporary location first before copying to the target,
		// if the file size of the files are the same. If the remote file system is NFS mounted
		// from the host, we end up with a truncated file otherwise.
		boolean copyViaTemp = true;
		File tempFile = null;

		// Create the file transfer item
		FileTransferItem item = new FileTransferItem(new Path(localFilePath), remoteFilePath);
		item.setProperty(IFileTransferItem.PROPERTY_DIRECTION, "" + IFileTransferItem.HOST_TO_TARGET); //$NON-NLS-1$

		// Get the remote path file attributes
		IFileSystem.FileAttrs attrs = FileTransferService.getRemoteFileAttrs(peer, null, item);
		if (attrs != null) {
			IPath hostPath = item.getHostPath();
			if (hostPath.toFile().canRead()) {
				copyViaTemp = attrs.size == hostPath.toFile().length();
			}
		}

		// Copy the host file to a temporary location if needed
		if (copyViaTemp) {

			monitor.beginTask(Messages.TEGdbAbstractLaunchDelegate_downloading + " " + localFilePath + " to " + remoteFilePath, 200); //$NON-NLS-1$ //$NON-NLS-2$

			try {
				IPath hostPath = item.getHostPath();
				tempFile = File.createTempFile(Long.toString(System.nanoTime()), null);

				long tick = hostPath.toFile().length() / 100;

				FileInputStream in = new FileInputStream(hostPath.toFile());
				try {
					FileOutputStream out = new FileOutputStream(tempFile);
					try {
						int count;
						long tickCount = 0;
						byte[] buf = new byte[4096];
						while ((count = in.read(buf)) > 0) {
							out.write(buf, 0, count);
							tickCount += count;
							if (tickCount >= tick) {
								monitor.worked(1);
								tickCount = 0;
							}
						}
					}
					finally {
						out.close();
					}
				}
				finally {
					in.close();
				}
			}
			catch (IOException e) {
				// In case of an exception, make sure that the temporary file
				// is removed before re-throwing the exception
				if (tempFile != null) tempFile.delete();
				// Also the monitor needs to be marked done
				monitor.done();
				// Re-throw the exception finally
				throw e;
			}

			// Recreate the file transfer item to take the temporary file as input
			item = new FileTransferItem(new Path(tempFile.getAbsolutePath()), remoteFilePath);
			item.setProperty(IFileTransferItem.PROPERTY_DIRECTION, "" + IFileTransferItem.HOST_TO_TARGET); //$NON-NLS-1$
		} else {
			monitor.beginTask(Messages.TEGdbAbstractLaunchDelegate_downloading + " " + localFilePath + " to " + remoteFilePath, 100); //$NON-NLS-1$ //$NON-NLS-2$
		}

		// Transfer the file to the target
		final Callback callback = new Callback();
		FileTransferService.transfer(peer, null, item, monitor, callback);
		// Wait till the step finished, an execution occurred or the
		// user hit cancel on the progress monitor.
		ExecutorsUtil.waitAndExecute(0, callback.getDoneConditionTester(null));

		// Remove the temporary file
		if (tempFile != null) tempFile.delete();
	}

	public static IPeerNode getPeerNode(final String peerId) {
		if (peerId != null) {
			final AtomicReference<IPeerNode> parent = new AtomicReference<IPeerNode>();
			final Runnable runnable = new Runnable() {
				@Override
				public void run() {
					parent.set(ModelManager.getPeerModel().getService(IPeerModelLookupService.class).lkupPeerModelById(peerId));
				}
			};
			Protocol.invokeAndWait(runnable);
			return parent.get();
		}
		return null;
	}

	public static IPeerNode getCurrentConnection(ILaunchConfiguration config) throws CoreException {
		String peerId = config.getAttribute(IRemoteTEConfigurationConstants.ATTR_REMOTE_CONNECTION, ""); //$NON-NLS-1$
		IPeerNode connection = getPeerNode(peerId);
		if (connection == null) {
			abort(Messages.TEHelper_connection_not_found, null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
		}
		return connection;
	}

	public static ProcessLauncher launchCmd(final IPeer peer, String peerName, String command, Listener listener, SubProgressMonitor monitor, ICallback callback) throws CoreException {
		if (command != null && !command.trim().equals("")) { //$NON-NLS-1$
			String[] args = StringUtil.tokenize(command, 0, true);
			if (args.length > 0) {
				String cmd = args[0];
				String[] arguments = null;
				if (args.length > 1) {
					arguments = Arrays.copyOfRange(args, 1, args.length);
				}
				return launchCmd(peer, peerName, cmd, arguments, listener, monitor, callback);
			}
		}
		return null;
	}

	public static ProcessLauncher launchCmd(final IPeer peer, String peerName, String remoteCommandPath, String arguments, Listener listener, SubProgressMonitor monitor, ICallback callback) throws CoreException {
		String[] args = arguments != null && !"".equals(arguments.trim()) ? StringUtil.tokenize(arguments, 0, true) : null; //$NON-NLS-1$
		return launchCmd(peer, peerName, remoteCommandPath, args, listener, monitor, callback);
	}

	public static ProcessLauncher launchCmd(final IPeer peer, String peerName, String remoteCommandPath, String[] args, Listener listener, SubProgressMonitor monitor, ICallback callback) throws CoreException {
		if (remoteCommandPath != null && !remoteCommandPath.trim().equals("")) { //$NON-NLS-1$
			monitor.beginTask(NLS.bind(Messages.TEHelper_executing, remoteCommandPath, args), 10);

			// Construct the launcher object
			ProcessLauncher launcher = new ProcessLauncher();

			Map<String, Object> launchAttributes = new HashMap<String, Object>();

			// Compute the terminal title if possible
			if (args != null && args.length > 0) {
				StringBuilder title = new StringBuilder();
				IPath p = new Path(remoteCommandPath);
				// Avoid very long terminal title's by shortening the path if it has more than 3 segments
				if (p.segmentCount() > 3) {
					title.append(".../"); //$NON-NLS-1$
					title.append(p.lastSegment());
				} else {
					title.append(p.toString());
				}

				for (String arg : args) {
					if (arg.matches(":[0-9]+")) { //$NON-NLS-1$
						title.append(arg);
						break;
					}
				}

				String name = peerName != null ? peerName : peer.getName();
				if (name != null && !"".equals(name)) { //$NON-NLS-1$
					title.append(" [" + name + "]"); //$NON-NLS-1$ //$NON-NLS-2$
				}

				if (title.length() > 0) launchAttributes.put(ITerminalsConnectorConstants.PROP_TITLE, title.toString());
			}

			launchAttributes.put(IProcessLauncher.PROP_PROCESS_PATH, spaceEscapify(remoteCommandPath));
			launchAttributes.put(IProcessLauncher.PROP_PROCESS_ARGS, args);

			launchAttributes.put(ITerminalsConnectorConstants.PROP_LOCAL_ECHO, Boolean.FALSE);

			boolean outputConsole = true;
			if (outputConsole) {
				launchAttributes.put(IProcessLauncher.PROP_PROCESS_ASSOCIATE_CONSOLE, Boolean.TRUE);
			}

			// Fill in the launch attributes
			IPropertiesContainer container = new PropertiesContainer();
			container.setProperties(launchAttributes);

			// If the line separator setting is not set explicitly, try to
			// determine it automatically (local host only).
			if (container.getProperty(ITerminalsConnectorConstants.PROP_LINE_SEPARATOR) == null) {
				// Determine if the launch is on local host. If yes, we can
				// preset the line ending character.
				final AtomicBoolean isLocalhost = new AtomicBoolean();

				Runnable runnable = new Runnable() {
					@Override
					public void run() {
						if (ITransportTypes.TRANSPORT_TYPE_TCP.equals(peer.getTransportName()) || ITransportTypes.TRANSPORT_TYPE_SSL.equals(peer.getTransportName())) {
							isLocalhost.set(IPAddressUtil.getInstance().isLocalHost(peer.getAttributes().get(IPeer.ATTR_IP_HOST)));
						}
					}
				};

				if (Protocol.isDispatchThread()) runnable.run();
				else Protocol.invokeAndWait(runnable);

				if (isLocalhost.get()) {
					container.setProperty(ITerminalsConnectorConstants.PROP_LINE_SEPARATOR, Host.isWindowsHost() ? ILineSeparatorConstants.LINE_SEPARATOR_CRLF : ILineSeparatorConstants.LINE_SEPARATOR_LF);
				}
			}

			if (listener != null) {
				container.setProperty(IProcessLauncher.PROP_PROCESS_OUTPUT_LISTENER, new StreamsDataReceiver.Listener[] { listener });
			}
			// Launch the process
			launcher.launch(peer, container, new Callback(callback) {
				@Override
				protected void internalDone(Object caller, IStatus status) {
					if (!status.isOK()) {
						System.out.println(status.getMessage());
					}
					super.internalDone(caller, status);
				}
			});
			monitor.done();
			return launcher;
		}
		return null;
	}

	/**
	 * Throws a core exception with an error status object built from the given message, lower level
	 * exception, and error code.
	 *
	 * @param message the status message
	 * @param exception lower level exception associated with the error, or <code>null</code> if
	 *            none
	 * @param code error code
	 */
	public static void abort(String message, Throwable exception, int code) throws CoreException {
		IStatus status;
		if (exception != null) {
			MultiStatus multiStatus = new MultiStatus(Activator.getUniqueIdentifier(), code, message, exception);
			multiStatus.add(new Status(IStatus.ERROR, Activator.getUniqueIdentifier(), code, exception
			                .getLocalizedMessage(), exception));
			status = multiStatus;
		}
		else {
			status = new Status(IStatus.ERROR, Activator.getUniqueIdentifier(), code, message, null);
		}
		throw new CoreException(status);
	}

	public static String spaceEscapify(String inputString) {
		if (inputString == null) return null;

		return inputString.replaceAll(" ", "\\\\ "); //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * Returns the string preference value for the given key. The method
	 * allows overwriting the preference value via a system property.
	 *
	 * @param key The preference key. Must not be <code>null</code>.
	 * @return The preference value or <code>null</code> if the preference key does not exist.
	 */
	public static String getStringPreferenceValue(String key) {
		Assert.isNotNull(key);

		// Try system properties first
		String value = System.getProperty(key, null);
		// If not set, try the preferences
		if (value == null || "".equals(value)) { //$NON-NLS-1$
			value = Activator.getScopedPreferences().getString(key);
		}
		return value;
	}

	/**
	 * Returns the list preference value for the given key. The method
	 * allows overwriting the preference value via a system property.
	 *
	 * @param key The preference key. Must not be <code>null</code>.
	 * @return The preference value or <code>null</code> if the preference key does not exist.
	 */
	public static List<String> getListPreferenceValue(String key) {
		Assert.isNotNull(key);

		List<String> list = null;
		String value = getStringPreferenceValue(key);
		if (value != null && !"".equals(value)) { //$NON-NLS-1$
			list = Arrays.asList(value.split("\\s*,\\s*")); //$NON-NLS-1$
		}

		return list;
	}

}

Back to the top