Архив

Archive for the ‘programming’ Category

Результат двухдневных извращений с SSHTools

Задача: из Java удаленно по SSH запустить приложений и забрать log-файл.

Два дня копался с SSHTools, задолбался, посмотрел JSch – ужаснулся. В итоге лень взяла вверх и тупо решил использовать готовые задачи из Apache Ant sshexec и scp с помощью AntBuilder из GDK (Groovy JDK). Смотрим, что получилось:

// SSHRunner.java
import groovy.util.AntBuilder;

import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SSHRunner {

 private final static Log LOG = LogFactory.getLog(SSHRunner.class);

 public final static int DEFAULT_SSH_PORT = 22;

 private int port;
 private String host, username, password;

 private AntBuilder builder = new AntBuilder();

 public SSHRunner(String host, String username, String password) {
 this(host, DEFAULT_SSH_PORT, username, password);
 }

 public SSHRunner(String host, int port, String username, String password) {
 if (StringUtils.isEmpty(host) || port < 1 || StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
 throw new IllegalArgumentException("All parameters must be at least one character");
 }

 this.host = host;
 this.port = port;
 this.username = username;
 this.password = password;
 }

 @SuppressWarnings("serial") public SSHRunner sshexec() {
 builder.invokeMethod("sshexec", new HashMap() {{
 put("host", host);
 put("trust", "true");
 put("port", Integer.toString(port));
 put("username", username);
 put("password", password);
 put("command", "cscript c:\\test.vbs");
 }});
 return this;
 }

 @SuppressWarnings("serial") public SSHRunner scp(final String filepath) {
 builder.invokeMethod("scp", new HashMap() {{
 put("trust", "true");
 put("port", Integer.toString(port));
 put("remoteFile", String.format("%s:%s@%s:c:\\testfile.txt", username, password, host));
 put("localTofile", filepath);
 }});
 return this;
 }

 public static void main(String[] args) {
 new SSHRunner("127.0.0.1", "admin", "password").sshexec().scp("/home/dulanov/Desktop/test.txt");
 }
}
Рубрики:java Метки: , , , , ,

iBatis enum type handler with Mockito

How to handler multiple-values String-based Enums in Java for Apache iBatis with Mockito unit test: EnumTypeHandlerImplTest, TypeHandlerCallback.

Рубрики:java

Команда для удаление всех rubygems

gem list | cut -d» » -f1 | xargs sudo gem uninstall –all (github’s gist)

Первоисточник: Painless Cleanup of Ruby Gems With Similar Names. А если возникли какие-то проблемы с удалением, то вам наверняка сюда.

Рубрики:linux, ruby Метки: , ,

Самое лучшее введение в язык программирования Haskell

Серия вводных статей на O’Relly про язык программирование Haskell – это лучшее что я пока ввидел, кратко и очень доходчиво:

An Introduction to Haskell, Part 1: Why Haskell

Introduction to Haskell, Part 2: Pure Functions

Introduction to Haskell, Part 3: Monads

Рубрики:haskell

Решето Эратосфена: Java vs. Haskell

Сентябрь 23, 2008 dulanov 1 комментарий

Как говорится, почувствуйте разницу, Java:

import java.util.Arrays;

public class PrimeNumbers {

	public static boolean[] getSieve(int n) {
		boolean[] primes = new boolean[n + 1];
		Arrays.fill(primes, 2, n + 1, true);
		for (int i = 2; i * i <= n; i++) {
			if (primes[i]) {
				for (int k = i * i; k <= n; k += i) {
					primes[k] = false;
				}
			}
		}
		return primes;
	}
}

vs. Haskell:

primes = sieve [2..]
    where
        sieve (x:xs) = x:sieve (filter ((/= 0).(`mod` x)) xs)

Читать дальше…

Рубрики:haskell, java

В помощь изучающим SICP

Когда только столкнулся с этой замечательной книгой, то постоянно испытывал недостаток альтернативных решений упражнений, теперь же это больше не проблема:

А также решения на других языках программирования:

Рубрики:programming

Идея проекта challenge

Февраль 27, 2007 dulanov 3 comments

В своей недавной заметке, посвященной академическим и промышленным языкам программирования я попытался, с одной стороны, сформировать самодостаточный базис для понимания всех существующих парадигм программирования (академические языки), а с другой стороны тех из них что реально используются на практике (промышленные языки). Оказалось что это не одни и те же языки!

В этой заметке я продолжу обсуждение затронутой темы, но немного в другой плоскости. Я расскажу об идеи проекта challenge, которую давно вынашиваю. Цель проекта challenge – практическое сравнение языков программирования с целью выявления их сильных и слабых качеств. Этот проект должен облегчить выбор языка программирования исходя из специфики задачи, которую необходимо решить.

Читать дальше…

Рубрики:challenge, opinion

Recomended Weekly Link’s (from 13.02.2007)

Interesting to me articals for last week:

  • OSGi Tutorials

    One of the challenges when starting out with OSGi is finding information on the basics.

  • Getting started with OSGi: Your first bundle

    Over the next week or two, EclipseZone will be running a series of short posts on OSGi. Taken together they should form a smooth path into mastering the art of OSGi programming, but each post will introduce just one new technique and it should be possible to work through in under ten minutes. Also, we want to show how simple OSGi development can be, so we will not be using Eclipse for development – just a text editor and the basic command line tools will do. So, welcome to the «Getting started with OSGi» series.

  • A Comparison of Eclipse Extensions and OSGi Services

    Since Eclipse adopted the OSGi runtime in version 3.0, there has been some tension between the Extension Registry, which has been a feature of Eclipse from its beginning, and the Service Layer, which came from OSGi and pre- existed the involvement of Eclipse. The cause of the tension is that these two models overlap somewhat, and because they are both intended to solve very similar problems. However “the Devil is in the details”, and these two models are different enough to make it impractical for them to be merged. Therefore developers of Eclipse plugins and RCP applications need to make a choice between the two.

Рубрики:java

Recomended Weekly Link’s (from 19.01.2007)

Interesting to me articals for last week:

  • Using maven-proxy to setup an internal maven repository

    When you’re using maven at your company, you almost always want to setup local maven repository…

  • Why I should learn Lisp

    Still I do not think Lisp is going to make mainstream, yet I need to learn Lisp to be a better fit in today’s world of changing programming paradigms.

  • Wicket – (another) Java Web Framework: My First Impressions

    If you are looking for something lightweight that will take a few minutes to learn, Wicket is not for you. If you are looking for a component-oriented approach, Wicket is a contender.

  • Free CSS Layouts And Templates

    As a web-developer you don’t have to re-invent the wheel all the time. If it just has to work, and has to be valid, and has to have a nice, visually appealing design hierarchy, you just can use css-techniques developed in the web-dev-community over the last few years. If you take a look around, you’ll find many templates, which include basic (X)HTML/CSS-markup.

  • The Rise of OSGi

    If you’re looking to create a plugin-based application, or to add a plugin system to your existing application, then you should look into OSGi.

Рубрики:java

Recomended Weekly Link’s (from 20.12.2006)

Interesting to me articals for last week:

Рубрики:java