суббота, 28 августа 2021 г.

Мальчик с феноменальной памятью

Team lead'ам о "мальчике с феноменальной памятью" (кто помнит этот анекдот, посмейтесь), занимающимися подбором персонала на работу - осторожно, крутой развод! Прочим будет весьма забавно прочитать сей пост, не пожалеете 🙂 Получил урок на собственном опыте. Навеяло написать после разговора с нашим HR которая давече уговаривала меня рассмотреть кандидатуру, который напрочь отказывался от live coding (кто не в теме - просьба продемонстрировать способность программировать вживую для решения заданных задач) на интервью. Довелось столкнуться с кандидатом, который теоретически просто "отстреливал" всё что у него не спросишь с весьма убедительной манерой общения. Немного насторожило то, что он сидел по стойке... т.е. сидке "смирно" (рассказывал что служил долго, но дело не в этом), и (особенно) на вопрос о том, насколько он готов заниматься (если что) вопросами, которые "чуть в стороне" от девелопмента (кто в теме, поймут насколько это бывает "больно" разработчикам, что может их отпугнуть), а именно (например) "потестировать перед релизом если тестировщики не успевают" или подобное, кандидат "отрапортовал" что "ну, я человек подневольный, что скажут, то и буду делать"... у меня в мозгах чуть "подвисло"... опять таки, кто в теме, сразу почуют неладное - ни один программист такое не скажет, ну не свойственно совершенно это нашему брату, тем более на рынке, где пять мест на одного толкового кандидата... Но ладно, я "схавал", может особенный человек, может много лет армии таки мозги подмыла, такое... Так вот, кроме того, что он "оттараторивал" любые теоретические вопросы, у него (!!!) был канал на youtube где он рассматривал сложные задачи по программированию (а-ля LeetCode и подобные) - в общем фарш по полной, на скрининге вы подумаете "ох нифигасе какой крутой кандидат мне попался, надо брать по-любому". А вот теперь самое интересное - когда мы дошли до live coding он оказывается... оперный театр... ЛЫКА НЕ ВЯЖЕТ! Пытался присобачить (не могу сказать по-другому) некий "крутой" алгоритм сортировки где-то из того же литкода (сказав о нём теоретически только) туда где он вообще ни к селу ни к городу... Оправдывается "я сегодня не спал, проблемы были", "на вашем сайте контраст плохой, я не вижу ничего", "да у меня тут знаете сколько мониторов, я теряюсь что шарить...", "да вы гляньте мой ютюб канал, я там и не такое лабаю", и т.д. Ну мы предложили организовать вторую сессию интервью, что бы он перед ней точно выспался, на которую он вначале согласился, а позже отменил...... Вот такое бывает, ребята 🙂 Походу человек с отличной памятью и контактами в IT сфере узнал что нужно теоретически для прохождения интервью, вызубрил вообще всё назубок, нашёл решения крутых задач, скопировал в свой канал на YouTube с очень умным лицом (и стойкой, т.е. сидкой "смирно") и задурманивает айтишные конторы... А ведь существую такие, и много, некоторые даже рекламируют (для привлечения) то, что интервью у них без лайв кодинга - так можно шикарно попасть на такого разводчика... учитывая то, что процедура on-boarding (ввода в курс дела, когда от кандидата ничего не требуется, кроме усвоения информации о разработке и разрабатываемом продукте по началу) длится до месяца, потом месяц-два когда можно постепенно допетрить что ... король-то голый... плюс время, за которое по контракту нужно предупредить человека об увольнении... разводчик может на ровном месте поднять 10-15 а то и больше штук баксов ))) и вперёд дальше по интервью, а айтишных контор-то на наш час доуя... А кстати можно и намного больше поднимать, понимая, что ты ничего на самом деле не сделаешь всё равно, продолжать собеседоваться не останавливаясь, запараллеливая процесс., устраиваясь в несколько контор одновременно, а ещё и фриланс подключить... Вот такое дело, ребятки 🙂 Так что дорогие кандидаты, которые действительно отказываются от лайв кодинга по причине проблемы "стойки за спиной", из-за чего многие впадают в ступор (в чём частично кстати и моя проблема) - простите и поймите, но я без лайв кодинга отныне "зась", предупреждайте о вашей проблеме, я пойму и буду делать большую на это скидку, но я обязан увидеть от кандидата "поток его мыслей" в процессе программирования, никак по-другому.

понедельник, 30 ноября 2020 г.

WSDL optimization tool

Some WSDLs are huge but are necessary to use for testing. For example SforceService.wsdl is huge and takes almost a minute to load in some tools and also it will cause unnecessaary delays on each call in runtime (e.g. I needed to wait about 10-15 minutes to complete a test which had many service calls in the application I develop). Here is the wsdl-optim WSDL optimization tool written on Java allowing to cut out everything else besides particular operations used including all related definitions. Also it can be used to cut off forgotten unused in any operation definitions. Known issues: when actual type can be successor of some other type (contains "base" attribute link to the parent) it can be cut by the tool as it cuts out all unreferenced directly types thus all childs too if there is no explicit link to them

пятница, 24 мая 2019 г.

Map value lazy initialization

Tired of the following pattern?


value = map.get(key);
if (value == null) {
    // Map value lazy initialization in act
    value = /* Init value */;
    map.put(key, value);
}
// Use value
Java2html


Here is the elegant solution from the Java 8:


import java.util.HashMap;
import java.util.Map;

public class MapInit {

  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    String ret;
    // Lambda function is called here as there is no value with "theKey" in the map
    // The same newly added value returned by the lambda function is returned 
    ret = map.computeIfAbsent("theKey", key -> "theValue");
    System.out.println(ret);
    System.out.println(map);
    // Lambda function isn't called here as there is the value with "theKey" in the map
    // Instead, the value with "theKey" is acquired from the map and returned
    ret = map.computeIfAbsent("theKey", key -> "theValue");
    System.out.println(ret);
    System.out.println(map);
    // The "mapping function" is called here as there is no value with "theInitiatedKey" in the map
    // The same newly allocated by the mapping function value is returned 
    ret = map.computeIfAbsent("theInitiatedKey", MapInit::valueInitiator);
    System.out.println(ret);
    System.out.println(map);
    // The "mapping function" isn't called here as there is the value with "theInitiatedKey" in the map
    // Instead, the value with "theInitiatedKey" is acquired from the map and returned
    ret = map.computeIfAbsent("theInitiatedKey", MapInit::valueInitiator);
    System.out.println(ret);
    System.out.println(map);
  }
  
  private static String valueInitiator(String key) {
    // The function is called if only the value with this key is absent from the map
    System.out.println("Initiating 'theInitiatedValue'");
    return "theInitiatedValue";
  }
}
Java2html

The output:

theValue
{theKey=theValue}
theValue
{theKey=theValue}
Initiating 'theInitiatedValue'
theInitiatedValue
{theKey=theValue, theInitiatedKey=theInitiatedValue}
theInitiatedValue
{theKey=theValue, theInitiatedKey=theInitiatedValue}


Inspired by the StackOverflow's question Java map.get(key) - automatically do put(key) and return if key doesn't exist?. Thanks for the solution to Roger Lindsjö.

вторник, 12 марта 2019 г.

HTTP replay tool

I searched through the internet but was not able to find anything around this and it was strange to me. I had an idea to resend full HTTP requests captured by e.g. Fiddler, TcpMon or even designed manually to the same or other host:port destination which is suitable e.g. running configured tasks on Jenkins, provide research to your code deployed on an Java Server such as Tomcat or JBoss, etc...

So I've created such tool and it is a part of the Simple Scheduler - you can download its binary and use couple of jars for this purpose, check the httpReplay.bat for instructions. The HTTP Replay tool description on the original site.
Beside simple single request the tool is able to perform batch simultaneous requests for e.g. load or DoS attack steadiness tests.

среда, 7 ноября 2018 г.

Restoring project's sources from Google Code

Thanks to the article How to recover a Google Code SVN Project and migrate to Github I found the way to download the SVN repository dump of my project J-Sche and was able to get the sources from there. Here are steps how I did it on Windows:

1. Download the SVN dump of the necessary project from the Google Code archive specifying the name of the project as red text in this link: https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/j-sche/repo.svndump.gz - just put this link into web browser address bar, click "enter" and the "repo.svndump.gz" dump file should be downloaded.
2. Un-gzip the file using any convenient application. I used Far Manager for this - locate desired location where to put decompressed file in one panel, locate the in the "repo.svndump.gz" in the opposite panel, click "ctrl + page down" to enter the archive, click F5 to copy the only "repo.svndump" file in it to the opposite panel's location - this is the easiest way to decompress it from the archive to the specified location.
3. Install Visual SVN Server, run it, add a user via right click on "Users", specifying "Create User...".
4. Right-click on "Repositories", select "Import Existing Repository", specify "Load repository from a dump file" and point the decompressed "repo.svndump", give a name to this repository. Now it should be appeared under the "Repositories". Open it, right click on the repository you've just created, specify "Copy URL to Clipboard".
5. Install the Tortoise SVN, go to a location you'd like to download project sources to using Explorer, right click here and choose "SVN Checkout". Tortoise' "Checkout" window should appear and the link, copied in the step 4 should appear in "URL of repository" automatically. Just click "OK" and the project sources from the repository content should be downloaded here.

понедельник, 11 сентября 2017 г.

Simple scheduler on Java

Let me introduce my project

The scheduler running as Windows Service isn't built on Quartz, with it's own easy-ro-read simple user-friendly configuration.

воскресенье, 20 апреля 2014 г.

Building Windows Service on Java using Apache Commons Daemon


I've came up with a pretty nice solution to realize the Windows Service using Java with help of Apache Commons Daemon. procrun.exe is used in Windows for that approach. It appears this approach is the potential candadate for the best practice so I want to share it with you. And of course I would like you to judge it - please welcome to comment!

ACD allows to use several methoods to execute the java application. For example you can use StartParams and StopParams along with StartClass and StopClass to use one method to start and stop the application - in this case you need to parse the corresponding parameter in the start/stop class to handle the corresponding action. You also can use different methods to execute the application specifying the StartMode and StopMode ... I prefer to use JVM method specifying different methods to start and stop the application.
To implement this I use StartMethod and StopMethod along with StartClass and StopClass to start and stop my service.

To examine and run following examples you need to download the sources from here or exporing the complete project JSche Simple Scheduler.

First, to learn the basics let's consider simplified example. To test it extract the archieve, build the maven project (I used maven 3 to assemble it) with "mvn package" command. Copy the resulted JavaWindowsServiceUsingCommonsDaemon-0.0.1-SNAPSHOT.jar to the simpleExample folder. Copy corresponding prunsrvXX.exe from the "bin" folder to the simpleExample too. Run the install_service.bat, check "Services". You should see new "Test Service" here. "logs" folder with couple of files iin it should be created. Now start the service in "Services". Check the console.log - you should detect logs messages dynamically added here.

Here is the RandomLoggerService.java class file to work as the service:

package test.service;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


/*
 * A Modified version of Commons Daemon provided sample ProcrunService
 * The original can be found here
 * http://svn.apache.org/viewvc/commons/proper/daemon/trunk/src/samples/ProcrunService.java?view=markup
 */

/*

 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 *
 */

/**
 * Sample service implementation for use with Windows Procrun.
 <p>
 * Use the main() method for running as a Java application. Use the
 * start() and stop() methods for running as a jvm (in-process) service
 */
public class RandomLoggerService implements Runnable {

  /** The Constant MS_PER_SEC. */
  private static final long MS_PER_SEC = 1000L// Milliseconds in a second

  /** The logger thread. */
  private static Thread loggerThread; // start and stop are called
                          // from different threads
  /** The Constant random. */
  private static final Random random = new Random();

  private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");

  private static void log(String message) {
    System.out.println(df.format(new Date()) + message);
  }

  /**
   * This method simulates performing the work of the service. In this case, it just logs
   * a message any time between 1-5 seconds.
   * A real logging application would get its log messages from a queue or socket etc.
   */
  public void run() {
    log("Thread started");
    
    while (true) {
      long sleepTime = random.nextInt(41;
      
      try {
        log("pausing " + sleepTime + " seconds");
        Thread.sleep(sleepTime * MS_PER_SEC);
      catch (InterruptedException e) {
        log("Exiting");
        break;
      }
    }
  }

  /**
   * Start thread.
   
   */
  private static void startThread() {
    log("Starting the thread");
    loggerThread = new Thread(new RandomLoggerService());
    loggerThread.start();
  }

  /**
   * Start the jvm version of the service, and waits for it to complete.
   
   @param args
   *            ignored
   */
  public static void start(String[] args) {
    startThread();
    synchronized (loggerThread) {
      try {
        loggerThread.wait();
      catch (InterruptedException e) {
        log("'Wait' interrupted: " + e.getMessage());
      }
    }
  }

  /**
   * Stop the JVM version of the service.
   
   @param args
   *            ignored
   */
  public static void stop(String[] args) {
    if (loggerThread != null) {
      log("Stopping the thread");
      loggerThread.interrupt();
      synchronized (loggerThread) {
        loggerThread.notify();
      }
    else {
      log("No thread to interrupt");
    }
  }

  public static void main(String[] args) {
    // This method isn't used by the Apache Commons Daemon runner, it is defined to have a possibility
    // to emulate running the same as simple java application e.g. for the debug purpose
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        RandomLoggerService.stop(new String[] {});
      }
    });
    start(args);
  }
}
Java2html

2 methods are used here by Apache Daemon helper - "start" to start the service and "stop" to stop it. "main" function is given here to use the same class as java main class to have a possibility to run the same what Apache Daemon is doing for the class while it's being run as the service but in the console - to run it as a simple java application mode just run this class in the console.

The install_service.bat batch file to install the service:
rem Note you need to have JAVA_HOME to be set and point to the existed JDK

rem treat this folder as Application Home folder
set APP_HOME=%~dp0
rem remove last "\" from the path to Application Home
for %%F in ("%APP_HOME%") do set APP_HOME=%%~fF

set APP_JAR=%APP_HOME%\JavaWindowsServiceUsingCommonsDaemon-0.0.1-SNAPSHOT.jar
set START_CLASS=test.service.RandomLoggerService
set STOP_CLASS=%START_CLASS%
set START_METHOD=start
set STOP_METHOD=stop
set APP_LOGS_FOLDER=%APP_HOME%\logs
set APP_CONSOLE_LOG=%APP_LOGS_FOLDER%\console.log

if not exist "%APP_LOGS_FOLDER%" md "%APP_LOGS_FOLDER%"

prunsrv.exe //IS//TestService --DisplayName "Test Service" --Description "My Test Service" --LogPath "%APP_LOGS_FOLDER%"^
 --Install "%APP_HOME%\prunsrv.exe" --Jvm "%JAVA_HOME%\jre\bin\server\jvm.dll" --StartPath "%APP_HOME%" --StopPath "%APP_HOME%"^
 --Classpath "%APP_JAR%" --StartClass %START_CLASS% --StopClass %STOP_CLASS% --StartMethod %START_METHOD% --StopMethod %STOP_METHOD%^
 --StartMode jvm --StopMode jvm --StdOutput "%APP_CONSOLE_LOG%" --StdError "%APP_CONSOLE_LOG%"

Here is close to minimum set of settings in this batch file. As I've said previously "method" specification is used to setup the access to Service handler. So "start" method is used to start the service, per Daemon documentation it must not exit until the seervice should run. "stop" method is to stop the service. To uninstall the service use the uninstall_service.bat.

Now let's switch to the most interesting set of batch files in "bin" folder - copy the same prunmgr.exe and JavaWindowsServiceUsingCommonsDaemon-0.0.1-SNAPSHOT.jar to that folder. Install the service using the similar batch file. It installs the service and configures it using the update_config.bat call. This file is intended to update the service configuration any time you need to change it. Just edit the update_config.bat and run it once. After that you need to (re)start the service for settings to take effect. Settings are stored in the registry. So next time when you are starting the service again they are retaken from there. E.g. you can uncomment the string setting the remote debugging ("-Xdebug" etc.) and after you restart the service you can access it to perform the remote debugging.
You can also use config_manager.bat to execute the UI tool allowing to edit the service settings in the dialog box. To apply these changes you also need to restart the service for settings to take effect. Note that if you run update_config.bat again after it will reset all parameters to the state kept in this batch file.
run_in_console.bat allows to run your service application in the console mode. You may find necessary to stop the same service to avoid conflicts between two simultaneous processes of the same application.
It's necessary to rename the procrun.exe for your particular application so in the "tasks list" you can see the appropriate executable name corresponding to your application name e.g. if it is necessary to "kill" the process.
Note that update_config.bat file contains some example options that are not needed by this class actually. These options should be removed in your application and replaced with any ones that are necessary for it. For instance proxy options are not necessary for this particular example.

Good luck :)