Архив

Archive for the ‘java’ 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

Решето Эратосфена: 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

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

Recomended Weekly Link’s (from 16.11.2006)

Interesting to me articals for last week:

  • Hibernate Performance Tips

    Some people I know are looking at porting their (very large) J2EE application from using a homegrown OR framework on top of Entity Beans with CMP (without CMR) to Hibernate, and they asked me for some tips. I‘m not claiming to be a Hibernate expert, but I‘ve used it on an enterprise product, added features, submitted patches, etc. so I know a bit.

  • Adopting OSGi as architectural asset for internal development

    In this article I’ll explain how many benefits can be obtained using a component oriented approach for software development adopting the OSGi model as the enabling component model.

  • Software design principles (mined from books)

    In this post I report a list of Software Design principles that I have mined from several books, papers.

  • Open Source ECM now? Think CPS!

    Please give this article a chance… I will try to explain the history of the CPS project, why it’s really about ECM, what is our approach, our passion…

  • Is Open Source capitalism, socialism or communism?

    At JBoss we always claim that FOSS is about a better way to develop, distribute and support software. Today’s software have tons of room to grow in terms of technical maturity, the economarket dynamics have tightened since the bubble forces The dirty little secret of the enterprise software model in today’s maturing market place is that, with the notable exception of a few players (MSFT and SAP included, ironically) the days of the hugely profitable sotware license are gone. In With the traditional software development model, your cost of sales, marketing and distribution is so high that these models completely depends on the for-pay license.

  • OSGi and Open Source ecosystem

    As InfoQ reported this summer, there is an increasing interested in OSGi and its related projects. I have created a table summarizing the status of OSGi in the field of Open Source community. Starting from available open source container, I searched about projects exploiting OSGi and their level of adoption of this technology.

Рубрики:java

Recomended Weekly Link’s (from 08.11.2006)

Interesting to me articals for last week:

  • Steve Ebersole on Hibernate 3.2

    Steve Ebersole is principal software engineer with JBoss and, along with Emmanuel Bernard, a lead on the Hibernate project. Following the release of Hibernate 3.2, Artima spoke with Ebersole about new features, Hibernate’s support for EJB 3 persistence, and upcoming Hibernate features.

  • Distributing synchronization across threads

    The Java keyword, synchronized, is the simplest form of concurrency control in Java. With the advent of the work by Doug Lea and notible others on the new java.util.concurrent package, there are more tools. When dealing with highly contested resources, distributing the locking is key.

  • Why REST Failed

    HTTP is based on four basic operations: GET, PUT, POST, and DELETE.

  • In defense of J2EE’s complexity

    J2EE bashing seems to be the flavour these days. While I do agree that J2EE does seem tedious at times, especially when you compare it with the likes of Ruby on Rails, I still realize (and appreciate) why and how J2EE got to be the way it is.

Рубрики:java

Recomended Weekly Link’s (from 27.10.2006)

Interesting to me articals for last week:

  • How Do Java’s Lists Measure Up? Comparing Arrays, Lists, and Maps

    Java offers several solutions for storing objects in an ordered list: arrays, Lists, and Maps—to mention the best known. This article analyzes the performance benefits and drawbacks of these lists using several examples.

  • The Role of the Enterprise Service Bus

    Mark Richards tells us what an ESB is, its role, what capabilities it provides, and the various ways an ESB can be implemented. He takes a close look at the JBI specification (JSR-208) and explains what impact it will have with the ESB world. This will teach you how to determine your own specific requirements for an ESB and then match these requirements to the product space.

  • Short, concise and readable code – invert your logic and stop nesting already!

    In the artical was described an useful method template:

    [return value] [method name](parameters) [throws clause] {
    [check pre conditions]

    [core logic]
    }

    The benefits to writing code in this stlye are

    * loose coupling – blocks are not dependent. You can add/subtract sections of code without having to worry about the surrounding logic
    * linear flow – mentally, it’s easier to grok links in a chain because they require small, focused amounts of brain power. A stack (nested code blocks) requires you to keep state, so the brain power required is additive for each level of nesting you introduce.

  • Do you really need a Persistence Layer?

    Continuing from my earlier post about building an AJAX / SOAP App in 15 minutes, the only way to build an app this fast is KISS. If you’re worrying about EJBs, Relational DBMS, or file storage, you’ve gone too far.

Рубрики:java

Recomended Weekly Link’s (from 17.10.2006)

This is my first weekly links issue. In its I will publicate articals interesting by me.

  • Stiff asks, great programmers answer

    With the help of public accessible e-mail adresses I asked 10 questions to a bunch of programmers that I consider very interesting people and I respect them for variuos things they created… But despite of this, I learn a lot of interesting stuff, so it was definietly a valuable experience.

  • Yes, we still need Transfer Objects with EJB3 JPA

    When we started our first project with the Java Persistence API (JPA) and EJB3, we made some decisions about the design… One of the decisions was to get rid of Data Transfer Objects. We took this decision because we firmly believed that the new annotated POJOs could be used a Transfer Objects between the different layers of our architecture. But it was not a good decision. Our database model was mapped to our entity model, and about 60-something classes aroused. I don’t think this is a complex model, but we can say it was ‘complex enough’. We found out very soon that the JPA POJOs were not good when they played the role of DTOs.

Рубрики:java