Quantcast
Channel: Redino blog
Viewing all 80 articles
Browse latest View live

CakePHP Get Version

$
0
0

To find out current version of CakePHP, we can use following methods:

  • CakePHP 2.x

Open lib/Cake/VERSION.txt file, the version number is at bottom of file.

 

  • CakePHP 3.x

Open vendor/cakephp/cakephp/VERSION.txt file, the version number is at bottom of file.

 

And if you want to get version in code, we can use following code

Configure::version()

 

Under the Hood

The Configure class is defined at lib/Cake/Core/Configuration.php file, reading the code we will find it’s actually reading the VERSION.txt file (the file we mentioned above) to find out current version as well.

The post CakePHP Get Version appeared first on Redino blog.


Hibernate ConstraintViolationException

$
0
0

In following code (a JUnit test method) I’m trying to delete specified users from database

@Test
    @Transactional
    public void testAddPermissions(){
        Session session = sysUserDao.getSessionFactory().openSession();
        List<SysUser> list = (List<SysUser>)session.createQuery("from SysUser where userName='adfadsfm'").list();
        if(list != null && list.size() > 0){
            session.delete(list.get(0));
            session.flush();
        }

        ...
    }

 

But when running above code, I got following exception:

org.hibernate.exception.ConstraintViolationException: could not execute batch

at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:132)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(BatchingBatch.java:111)
at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(AbstractBatchImpl.java:163)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(JdbcCoordinatorImpl.java:226)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:484)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at com.dfweb.service.impl.SysUserServiceImplTest.testAddPermissions(SysUserServiceImplTest.java:77)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (db_df.permission_sys_user, CONSTRAINT FK_2l5pbq5juqkbrg6rtqes6w1el FOREIGN KEY (users_id) REFERENCES sys_user (id))
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2055)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1467)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1135)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:123)
… 41 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (db_df.permission_sys_user, CONSTRAINT FK_2l5pbq5juqkbrg6rtqes6w1el FOREIGN KEY (users_id) REFERENCES sys_user (id))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2007)
… 44 more

 

Reason

This is because there is an RESTRICT reference for foreign key of permission_sys_user that references id column of sys_user table.

So deleting the SysUser entity and keep its related permissions in permission_sys_user table will break the foreign key constraint of permission_sys_user table (references sys_user table with default RESTRICT reference option).

 

Solution

Following is SysUser class related source code

@ManyToMany(cascade = { CascadeType.PERSIST,
      CascadeType.MERGE }, mappedBy = "users", targetEntity = Permission.class)
private Set<Permission> permissions;

 

One possible solution is to remove its related records in permission_sys_user table when deleting SysUser entity, so change SysUser to following will fix this issue:

@ManyToMany(cascade = { CascadeType.PERSIST,
      CascadeType.MERGE, CascadeType.REMOVE }, mappedBy = "users", targetEntity = Permission.class)
private Set<Permission> permissions;

Above code adds

CascadeType.REMOVE
  for
ManyToMany
  annotation’s
cascade
  attribute. This will make deleting SysUser entity will trigger deleting related Permission entities.

The post Hibernate ConstraintViolationException appeared first on Redino blog.

Ext JS Image Reload

$
0
0

In Ext JS, to reload or refresh an image, we can call updateSrc() method, and also setSrc() method is working as well.

var img = Ext.getCmp('img_a');
img.updateSrc('...'); // or img.setSrc('...');

 

And if the requested image is cached, we need use cache buster to avoid loading cached image.

Ext.create('Ext.Img', {
  src: 'http://redino.net/xxx.jpg?' + new Date().getTime()
});

 

Note that I found another post saying to use doComponentLayout method to refresh an image, but this method is deprecated since version 4.1.

The post Ext JS Image Reload appeared first on Redino blog.

Dom4j Writing File Not Working

$
0
0

Dom4j is a XML processing library which supports XPath, DOM, SAX,  JAXP. In this post we will see a problem that dom4j could not write document to file.

 

Following XML is sample data which we will save to file using dom4j.

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <payment creator_id="4"/>
</root>

To generate above XML and write it to file, following code will be used

Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
root.addElement("payment").addAttribute("creator_id", 4);
FileWriter writer = new FileWriter("payments.xml");
doc.write(writer);

Above code may generate an empty file with no content.

 

This is because the content is stored in buffer and not really written to file when calling

write
  method. To write to file, we should call
flush
  method or
close
  method.

So above code should be changed to

Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
root.addElement("payment").addAttribute("creator_id", 4);
FileWriter writer = new FileWriter("payments.xml");
doc.write(writer);
doc.flush();

Or

Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
root.addElement("payment").addAttribute("creator_id", 4);
FileWriter writer = new FileWriter("payments.xml");
doc.write(writer);
doc.close();

 

The post Dom4j Writing File Not Working appeared first on Redino blog.

Apache POI Sheet.getPhysicalNumberOfRows()

$
0
0

In the past I use following code to display first cell string of all rows.

for(int i=0; i<sheet.getPhysicalNumberOfRows(); i++){
            Row row = sheet.getRow(i);
            if(row == null || row.getCell(0) == null){
                System.out.println(row.getCell(0).getStringCellValue());
            }
        }

But above code will be incorrect if there is empty row.

 

Following is explanation from POI official documentation

Sheet.getPhysicalNumberOfRows()

Returns the number of physically defined rows (NOT the number of rows in the sheet)

This method will ignore empty rows, e.g. if a sheet last row is at row 7, but second row is empty,

getPhysicalNumberOfRows()
  will return 6.

 

Solution

To get row count of a sheet (no matter the row is empty or not), we should use

getLastRowNum()
  method.

So above code can be changed to

for(int i=0; i<=sheet.getLastRowNum(); i++){
            Row row = sheet.getRow(i);
            if(row == null || row.getCell(0) == null){
                System.out.println(row.getCell(0).getStringCellValue());
            }
        }

Because

getLastRowNum()
  method returns 0-based row index, so we use
i<=sheet.getLastRowNum()
  as the loop condition.

The post Apache POI Sheet.getPhysicalNumberOfRows() appeared first on Redino blog.

Java HTML Encoding (HTML Entities)

$
0
0

Some XSS attacks can be prevented by using HTML Encoding.

HTML encoding function is built into many languages, In .NET

WebUtility.HtmlEncode
  can do it, in PHP we can use
htmlentites
  function, in Python
cgi.escape
  can be used.

But there is no built-in function to do HTML Encode (or HTML Entities) in Java.

We can use Apache Commons Lang library to do this work.

 

import org.apache.commons.lang.StringEscapeUtils;

System.out.println(StringEscapeUtils.escapeHtml("<>"));

Above code will output following result using HTML Encoding

&lt;&gt;

 

Note that not all XSS attacks can be prevented by HTML encoding (https://stackoverflow.com/questions/53728/will-html-encoding-prevent-all-kinds-of-xss-attacks).

The post Java HTML Encoding (HTML Entities) appeared first on Redino blog.

Python TypeError: Error when calling the metaclass bases

$
0
0

When running the code, I got following error:

TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)

 

The source code is like following:

AboutWindow.py

import GitFtpWindow

class AboutWindow(GitFtpWindow):
    ...

 

GitFtpWindow.py

from PySide.QtGui import *

class GitFtpWindow(QWidget):
   def __init__(self):
      QWidget.__init__(self)
      self.setWindowTitle('Ftp-Git')

 

This is because in AboutWindow.py file, the GitFtpWindow identifier is a package, but not a class.

To fix this problem, we need modify AboutWindow.py file like following:

from GitFtpWindow import GitFtpWindow

class AboutWindow(GitFtpWindow):

 

 

The post Python TypeError: Error when calling the metaclass bases appeared first on Redino blog.

mongodb InternalError: failed to create service entry worker thread

$
0
0

Following is content from /var/log/mongodb/mongod.log:

2017-12-18T01:21:41.953+0800 W EXECUTOR [conn4444] Terminating session due to error: InternalError: failed to create service entry worker thread
2017-12-18T01:21:41.953+0800 I NETWORK [listener] end connection 127.0.0.1:36868 (1001 connections now open)
2017-12-18T01:21:41.953+0800 I NETWORK [listener] connection accepted from 127.0.0.1:36870 #4445 (1002 connections now open)
2017-12-18T01:21:41.954+0800 I – [listener] pthread_create failed: Resource temporarily unavailable
2017-12-18T01:21:41.954+0800 W EXECUTOR [conn4445] Terminating session due to error: InternalError: failed to create service entry worker thread
2017-12-18T01:21:41.954+0800 I NETWORK [listener] end connection 127.0.0.1:36870 (1001 connections now open)
2017-12-18T01:21:41.979+0800 I NETWORK [listener] connection accepted from 127.0.0.1:36872 #4446 (1002 connections now open)
2017-12-18T01:21:41.979+0800 I – [listener] pthread_create failed: Resource temporarily unavailable
2017-12-18T01:21:41.979+0800 W EXECUTOR [conn4446] Terminating session due to error: InternalError: failed to create service entry worker thread
2017-12-18T01:21:41.979+0800 I NETWORK [listener] end connection 127.0.0.1:36872 (1001 connections now open)

 

This problem occured after web request (which will create new MongoClient instance) started for a while, it’s not happened immediately, so it’s likely caused by the connection limit is reached.

Through the log we can find the connection count limit is about 1000.

 

Every time I open Mongo Console, I got startup warnings

MongoDB shell version v3.6.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.0
Server has startup warnings:
2017-12-19T16:29:45.510+0800 I STORAGE [initandlisten]
2017-12-19T16:29:45.510+0800 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-12-19T16:29:45.510+0800 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-12-19T16:29:46.006+0800 I CONTROL [initandlisten]
2017-12-19T16:29:46.006+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-12-19T16:29:46.006+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-12-19T16:29:46.006+0800 I CONTROL [initandlisten]
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten]
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is ‘always’.
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten] ** We suggest setting it to ‘never’
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten]
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is ‘always’.
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten] ** We suggest setting it to ‘never’
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten]
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 64000 files. Number of processes should be at least 32000 : 0.5 times number of files.
2017-12-19T16:29:46.008+0800 I CONTROL [initandlisten]
We can see the connection count limit is actually 1000.

 

So to fix this issue, either is to increase the connecton count limit, or to close the created MongoClient explicitly in code.
In my program every request a new MongoClient is created, I didn’t explicitly close it after using it. The solution is calling close method of MongoClient or using singleton MongoClient (the MongoClient library recommended this way for using connection pooling).

By using this method, the problem is solved.

The post mongodb InternalError: failed to create service entry worker thread appeared first on Redino blog.


HBase get column qualifiers by column family

$
0
0

To get column qualifiers by column family we can use following code

Get get = new Get(Bytes.toBytes("rowA"));
    Table table = conn.getTable(TableName.valueOf("merchants"));
    Result result = table.get(get);

    Map<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes("basicInfo"));
    for(Map.Entry<byte[], byte[]> entry:familyMap.entrySet()){
        System.out.println(Bytes.toString(entry.getKey()));
    }

Above code will outputs all column qualifer names of family map “basicInfo” in table “merchants”.

 

And following code shows different ways to retrieve HBase cell value

private void getData() throws IOException {
    Get get = new Get(Bytes.toBytes("row1"));
    Table table = conn.getTable(TableName.valueOf("merchants"));
    Result result = table.get(get);
    byte[] value = result.getValue(Bytes.toBytes("merchantNo"), Bytes.toBytes("string"));
    System.out.println(Bytes.toString(value));

    Map<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes("merchantNo"));
    for(Map.Entry<byte[], byte[]> entry:familyMap.entrySet()){
        System.out.println(Bytes.toString(entry.getKey()) + ", " + Bytes.toString(entry.getValue()));
    }
}

 

  • Get Cell by Family Map and Column Qualifier

byte[] value = result.getValue(Bytes.toBytes("merchantNo"), Bytes.toBytes("string"));

This line of code retrives cell value by family map “merchantNo” and column qualifier “string”

 

  • Get All Cells by Faimily Map

Map<byte[], byte[]> familyMap = result.getFamilyMap(Bytes.toBytes("merchantNo"));
for(Map.Entry<byte[], byte[]> entry:familyMap.entrySet()){
    System.out.println(Bytes.toString(entry.getKey()) + ", " + Bytes.toString(entry.getValue()));
}

result.getFamilyMap(Bytes.toBytes("merchantNo"))
  will return column family map with name “merchantNo”, it contains column qualifier name as key and cell value as value.
for(Map.Entry<byte[], byte[]> entry:familyMap.entrySet()){
    System.out.println(Bytes.toString(entry.getKey()) + ", " + Bytes.toString(entry.getValue()));
}

Above code will iterate the column family map, and outputs each column qualifier and its corresponding cell value.

The post HBase get column qualifiers by column family appeared first on Redino blog.

Intellij IDEA plugin development get selected text

$
0
0

To get selected text in a Intellij Platform Plugin project, we can use following code

public void actionPerformed(AnActionEvent e) {
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        String selectedText = editor.getSelectionModel().getSelectedText();
        selectedText = selectedText.replace("、", ",").replace(",", ",");
        selectedText.split("[,\\s]");
    }

 

The first line is used to get current editor object

Editor editor = e.getData(PlatformDataKeys.EDITOR);

 

Then call getSelectionModel and getSelectedText method to get selected text

String selectedText = editor.getSelectionModel().getSelectedText();

 

The last two lines is to to some operation for selected text, it’s unrelated to our goal.

 

 

The post Intellij IDEA plugin development get selected text appeared first on Redino blog.

Spring Cloud Zuul Ribbon custom rule not working

$
0
0

I need a custom Rule which can route requests to different service according to weight option (actually I want to deploy an A/B test service and only small percent of user will hit it), the code is like following

public class ConfigWeightRule extends RoundRobinRule {
    private Logger logger = LoggerFactory.getLogger("ConfigWeightRule");
    @Override
    public Server choose(Object key) {
        RequestContext currentContext = RequestContext.getCurrentContext();
        logger.info("LOG00120: currentContext: {} ", currentContext);

        int weight = 5;
        if (new Random().nextInt(100) > weight) {
            List<Server> abTestServers = this.getLoadBalancer().getAllServers().stream().filter(s -> ((DiscoveryEnabledServer) s).getInstanceInfo().getInstanceId().contains("ab-test")).collect(Collectors.toList());
            if (abTestServers.size() > 0) {
                return abTestServers.get(0);
            }
        }

        return super.choose(key);
    }
}

 

And following is application.yml configuration file

facade:
  ribbon:
    NFLoadBalancerClassName: com.netflix.loadbalancer.DynamicServerListLoadBalancer
    NFLoadBalancerRuleClassName: cn.jh.microservises.support.gateway.loadbalancer.rule.ConfigWeightRule

 

Adding breakpoints at constructor of ZoneAwareLoadBalancer and DynamicServerListLoadBalancer, then access the Zuul service via browser and I found ZoneAwareLoadBalancer constructor breakpoint is reached first.

public ZoneAwareLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter) {
    super(clientConfig, rule, ping, serverList, filter);
}

Inspect the value clientConfig->properties->NFLoadBalancerClassName, its value is still “com.netflix.loadbalancer.ZoneAwareLoadBalancer”, and the passed in rule is not my configured rule as well.

This means my configuration didn’t work.

 

Even I changed the class name to an invalid value, there is no error

facade:
  ribbon:
    NFLoadBalancerClassName: com.netflix.loadbalancer.DynamicServerListLoadBalancer
    NFLoadBalancerRuleClassName: aaa

 

In Spring Cloud documentation, under Customizing the Ribbon Client using properties section, it’s saying

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.

Checking maven pom file I found it’s using 1.1.0

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-zuul</artifactId>
   <version>1.1.0.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
   <version>1.1.0.RELEASE</version>
</dependency>

 

Changing them to 1.2.0 and run again, following exception is thrown

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ribbonRule' defined in org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.IRule]: Factory method 'ribbonRule' threw exception; nested exception is java.lang.IllegalArgumentException: Unknown class to load aaa for class interface com.netflix.loadbalancer.IRule named facade
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
	at org.springframework.cloud.context.named.NamedContextFactory.createContext(NamedContextFactory.java:110)
	at org.springframework.cloud.context.named.NamedContextFactory.getContext(NamedContextFactory.java:79)
	at org.springframework.cloud.context.named.NamedContextFactory.getInstance(NamedContextFactory.java:115)
	at org.springframework.cloud.netflix.ribbon.SpringClientFactory.getInstance(SpringClientFactory.java:111)
	at org.springframework.cloud.netflix.ribbon.SpringClientFactory.getClient(SpringClientFactory.java:49)
	at org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory.create(HttpClientRibbonCommandFactory.java:41)
	at org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory.create(HttpClientRibbonCommandFactory.java:30)
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:131)
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:84)
	at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112)
	at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197)
	at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:161)
	at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:120)
	at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96)
	at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116)
	at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81)
	at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:158)
	at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequestInternal(ZuulController.java:43)
	at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:147)
	at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:261)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:115)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.IRule]: Factory method 'ribbonRule' threw exception; nested exception is java.lang.IllegalArgumentException: Unknown class to load aaa for class interface com.netflix.loadbalancer.IRule named facade
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
	... 90 more
Caused by: java.lang.IllegalArgumentException: Unknown class to load aaa for class interface com.netflix.loadbalancer.IRule named facade
	at org.springframework.cloud.netflix.ribbon.PropertiesFactory.get(PropertiesFactory.java:58)
	at org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.ribbonRule(RibbonClientConfiguration.java:87)
	at org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration$$EnhancerBySpringCGLIB$$dae93cac.CGLIB$ribbonRule$4(<generated>)
	at org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration$$EnhancerBySpringCGLIB$$dae93cac$$FastClassBySpringCGLIB$$5a79f483.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
	at org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration$$EnhancerBySpringCGLIB$$dae93cac.ribbonRule(<generated>)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
	... 91 more

 

It’s because NFLoadBalancerRuleClassName is aaa, changing it to a valid name and try it again, it works now

 

 

The post Spring Cloud Zuul Ribbon custom rule not working appeared first on Redino blog.

Cannot install Docker on CentOS 6

$
0
0

Installing docker-ce on CentOS 6.9 got following error

Resolving Dependencies
--> Running transaction check
---> Package docker-ce.x86_64 0:18.03.1.ce-1.el7.centos will be installed
--> Processing Dependency: container-selinux >= 2.9 for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libseccomp >= 2.3 for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libsystemd.so.0(LIBSYSTEMD_209)(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: pigz for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: systemd-units for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libc.so.6(GLIBC_2.17)(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libseccomp.so.2()(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libsystemd.so.0()(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Running transaction check
---> Package docker-ce.x86_64 0:18.03.1.ce-1.el7.centos will be installed
--> Processing Dependency: container-selinux >= 2.9 for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libseccomp >= 2.3 for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libsystemd.so.0(LIBSYSTEMD_209)(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: systemd-units for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libc.so.6(GLIBC_2.17)(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libseccomp.so.2()(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
--> Processing Dependency: libsystemd.so.0()(64bit) for package: docker-ce-18.03.1.ce-1.el7.centos.x86_64
---> Package pigz.x86_64 0:2.3.4-1.el6 will be installed
--> Processing Conflict: docker-ce-18.03.1.ce-1.el7.centos.x86_64 conflicts docker-io
--> Finished Dependency Resolution
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: libsystemd.so.0(LIBSYSTEMD_209)(64bit)
Error: docker-ce conflicts with docker-io-1.7.1-2.el6.x86_64
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: libc.so.6(GLIBC_2.17)(64bit)
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: systemd-units
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: libseccomp >= 2.3
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: libseccomp.so.2()(64bit)
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: libsystemd.so.0()(64bit)
Error: Package: docker-ce-18.03.1.ce-1.el7.centos.x86_64 (docker-ce-stable)
           Requires: container-selinux >= 2.9
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

 

To install docker on CentOS 6, run the following command

yum install docker-io

 

Then run

docker --version

Its output is

Docker version 1.7.1, build 786b29d/1.7.1

 

We can see docker is installed successfully.

The post Cannot install Docker on CentOS 6 appeared first on Redino blog.

CentOS 6 Install netcat

$
0
0

Netcat is one utility in NMap toolset, it maybe named as nc, ncat or netcat on different Linux distributions. (It’s ncat on CentOS 6).

On CentOS 6 netcat is not installed by default, to install it we can run following command

yum install nmap

 

Then run following command to check netcat is installed correctly

ncat -v

 

The post CentOS 6 Install netcat appeared first on Redino blog.

GitLab took too much memory

$
0
0

The gitlab execution on our company internal server eats lots of memory, the server has 32G memory, and gitlab took more than half of it.

 

ps aux|sort -k4
I found there are lots of unicorn processes running, and each unicorn process is taking 1.5% memory
In
top
  command output it’s displaying as ruby process and took nearly 500MB resident memory (by default top is sorting by cpu usage, pressing < or > key to change sorting column)
ps aux|grep unicorn|wc -l
Running above command outputs 34, that means at most 34 unicorn processes are running (some other processes’ name also contain unicorn)..
Assume there are 30 real unicorn process running, each takes 500MB memory, then they will take 30*500MB=15GB memory
To decrease unicorn processes count, edit /etc/gitlab/gitlab.rb, and uncomment following line
#unicorn['worker_processes'] = 2

 

Next restart GitLab

gitlab-ctl restart

Now the memory usage is decreased.

 

(Note that running

gitlab-ctl reconfigure
  will not kill already running unicorn processes)

The post GitLab took too much memory appeared first on Redino blog.

Hibernate Query unexpected token: INTERVAL

$
0
0

I’m trying to fetch inventories which is opened at last month, for traditional SQL DATE_SUB function should be used here for date calculation. So the HQL is like following

select count(id) from Inventory where type=1 and agent.id=:userId and openTime>=CONCAT(YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', '21', ' 00:00:00')
 and openTime<=CONCAT(YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', '31', ' 23:59:59')

 

But following error appeared when running it in Hibernate QL Query Consonle in Intellij IDEA

unexpected token: INTERVAL near line 1, column 125 [select count(id) from com.dfweb.model.Inventory where type=1 and agent.id=:userId and openTime>=CONCAT(YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH)),
 '-', MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', '21', ' 00:00:00') and openTime<=CONCAT(YEAR(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH)), '-', '31', ' 23:59:59')]

 

Unfortunatelly the INTERVAL keyword is not supported in HQL.

 

Solution

An alternative is to calculate the date in Java and pass the result dates to HQL as parameters. The code is like following

def openedCount = (Integer)this.session.createQuery("select count(id) from Inventory where type=1 and agent.id=:userId and openTime>=:startTime and openTime<=:endTime")
                .setString("startTime", DateUtil.getLastMonthFirstDay()+" 00:00:00")
                .setString("endTime", DateUtil.getLastMonthLastDay()+" 23:59:59")
                .setParameter("userId", user.id)
                .uniqueResult()

 

Implementation code for DateUtil.getLastMonthFirstDay and DateUtil.getLastMonthLastDay

public static String getLastMonthFirstDay(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return new SimpleDateFormat(DATE_FORMAT).format(calendar.getTime());
	}

	public static String getLastMonthLastDay(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return new SimpleDateFormat(DATE_FORMAT).format(calendar.getTime());
	}

 

 

 

The post Hibernate Query unexpected token: INTERVAL appeared first on Redino blog.


Method.invoke throws java.lang.IllegalArgumentException: wrong number of arguments

$
0
0

Background

There is a private downloadFile method of ZhangyoobaoLeshuaMerchantRegister class, the method signature is like following

private ActionResult downloadFile(String url){

A unit test case for this method need be created, in this test case we need pass a null value as parameter to test whether this method can handle null parameter. But a private method cannot be accessed from the instance level. The solution is to use reflection to get the method, and set its accessiblity to public temporarily (by using the Method.setAccessible method).

 

First let’s see some code

@Test
    public void downloadFile() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        ChannelSecurityInfo securityInfo = new ChannelSecurityInfo();
        securityInfo.setMerchantNo("6124");
        securityInfo.setSecretKey("64c881c310cd42f1");
        ZhangyoobaoLeshuaMerchantRegister register = new ZhangyoobaoLeshuaMerchantRegister(securityInfo);
        Method method = register.getClass().getDeclaredMethod("downloadFile", String.class);
        method.setAccessible(true);
        Object result = method.invoke(register, "bing.com");
        System.out.println(result);

        result = method.invoke(register, null);
        System.out.println(result);
    }

Above Java code is the unit test case, it uses reflection to get the private method downloadFile of class ZhangyoobaoLeshuaMerchantRegister, and set the access level of this method to public, then call it with parameters. (Note that if setAccessible is not called to set method access level, Method.invoke will throw IllegalAccessException.)

But running this line 

result = method.invoke(register, null);
  will got following error
java.lang.IllegalArgumentException: wrong number of arguments

	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.jh.paymentchannel.channel.zhangyoobao.ZhangyoobaoLeshuaMerchantRegisterTest.downloadFile(ZhangyoobaoLeshuaMerchantRegisterTest.java:40)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

It’s because the second argument of Method.invoke() is

Object...
  (An Object[] array), its elements are arguments passed in to the method. Calling Method.invoke() with null as second argument is actually trying to call the method with no arguments, but downloadFile method requires one parameter, so it definitely raises IllegalArgumentException.

 

Solution

To fix this issue, change following line

result = method.invoke(register, null);

to

result = method.invoke(register, new Object[]{null});

This will pass null as first argument for downloadFile method.

new Object[]{null}
  is correspondding to the
Object...
  argument of Method.invoke(), it’s expanded like calling
downloadFile(null)
 .

 

The post Method.invoke throws java.lang.IllegalArgumentException: wrong number of arguments appeared first on Redino blog.

java.lang.NoClassDefFoundError: java/util/Base64

$
0
0

Problem

In the following code, Base64 is used to encode AES encrypted data bytes to plain text for transfering via URL query parameter.

public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getUrlEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
            log.warn("encryption failed", e);
        }
        return null;
    }

 

But when running this code on my coworker’s machine, following exception is thrown

java.lang.NoClassDefFoundError: java/util/Base64
	at net.redino.crypto.AES.encrypt(AES.java:49)
	at com.shopping.view.web.action.IndexViewAction.sqtx(IndexViewAction.java:947)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)

 

It’s because that my execution environment is Java 8, but my coworker is using Java 7, and java.util.Base64 is introduced in Java 8.

 

Solution

To fix this issue, we can use Base64 class from Apache Commons Codec.

First add commons codec dependency to maven pom.xml file.

<dependencies>
    ...
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
    ...
</dependencies>

Next import Base64 class from commons-codec

import org.apache.commons.codec.binary.Base64;

 

Finally replace 

Base64.getUrlEncoder().encodeToString
to
Base64.encodeBase64URLSafeString
.

So the code will become like following

public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.encodeBase64URLSafeString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
            log.warn("encryption failed", e);
        }
        return null;
    }

 

 

The post java.lang.NoClassDefFoundError: java/util/Base64 appeared first on Redino blog.

Spring disable transaction for method in transactional class

$
0
0

Overview

In Spring

@Transactional
  annotation can be used to indicate method should be run in transaction.

When

@Transactional
  is placed on method, this method will be run with transaction. And if it’s placed on a class, all methods of this class will run within transaction.

 

In MVC style application, we usually wrap business logic into a separate service class annotated with

@Service
  and
@Transactional
 , so every method will run within transaction. But how to disable transaction management for a specific single method in class which is annotated with
@Transactional
 ?

 

Solution

Add following code before the method which you want to disable transaction management for.

@Transactional(propagation = Propagation.NEVER)

Above code will tell Spring PlatformTransactionManager that transaction is not supported for this method, and transaction manager won’t create a new transaction if no transaction is existed.

And if a current transaction existed, exception will be thrown (An IllegalTransactionStateException with message “Existing transaction found for transaction marked with propagation ‘never'”).

 

The post Spring disable transaction for method in transactional class appeared first on Redino blog.

SSH WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

$
0
0

My cloud server moved to VPC from classic network just now, and connecting to it via SSH got following error

Connecting to upay...
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
91:65:8c:eb:63:86:5f:f2:b0:e6:77:d2:81:71:ef:2a.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts:1
RSA host key for x.x.x.x has changed and you have requested strict checking.
Host key verification failed.
Couldn't read packet: Connection reset by peer

 

Solution

It seems the server host key is changed, one way to solve this prolem is to remove the line containing server IP address from

/root/.ssh/known_hosts
 . Then connect to it by SSH again, it will ask you whether trust this new host key, like following message
Connecting to upay...
The authenticity of host 'x.x.x.x (x.x.x.x)' can't be established.
RSA key fingerprint is 91:65:8c:eb:63:86:5f:f2:b0:e6:77:d2:81:71:ef:2a.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Enter key, this new host key is added to

.ssh/known_hosts
  then.

 

Also you can obtain the host key from the remote server, and add it to

.ssh/known_hosts
  manually , but we won’t cover this method in detail.

The post SSH WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! appeared first on Redino blog.

Specified key was too long; max key length is 3072 bytes

$
0
0

 

alter table actionstatistics add unique(value, productId, productName, productSerialNumber, userPhone, userName, userId, type, statStartTime, statEndTime);

When running above statement to add unique index, following error happened.

[2018-03-28 11:38:24] [42000][1071] Specified key was too long; max key length is 3072 bytes

 

Table structure

CREATE TABLE `paymentstat` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `created` datetime DEFAULT NULL,
  `isCalculatedReward` bit(1) NOT NULL,
  `productId` int(11) DEFAULT NULL,
  `productName` varchar(255) DEFAULT NULL,
  `productSerialNumber` varchar(255) DEFAULT NULL,
  `statEndTime` datetime DEFAULT NULL,
  `statStartTime` datetime DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `userId` bigint(20) DEFAULT NULL,
  `userName` varchar(255) DEFAULT NULL,
  `userPhone` varchar(255) DEFAULT NULL,
  `value` varchar(255) DEFAULT NULL,
  `valueDouble` decimal(20,2) DEFAULT NULL,
  `actionStatisticsExpression_id` bigint(20) DEFAULT NULL,
  `user_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_d7fu0dasg9vq3w21qtvr6227o` (`actionStatisticsExpression_id`),
  KEY `FK_r852hjlpseh3ue8wd8gugd14d` (`user_id`),
  KEY `phone_idx` (`userPhone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

So the above index key length is value(255*3), productId(4), productName(255*3), productSerialNumber(255*3), userPhone(255*3), userName(255*3), userId(8), type(255*3), statStartTime(8), statEndTime(8)

Total length is 255*6*3 + 4 + 8*3=4618 is greater than 3072 bytes.

 

Note that the charset used is UTF8, so every character will occupy 3 bytes.

 

Solution

Then change to following statement, and the error is fixed.

alter table actionstatistics add unique(value, productId, productName(10), productSerialNumber(20), userPhone(12), userName(20), userId, type(10), statStartTime, statEndTime);

 

Another solution is to increase this 3072 bytes limit.

The post Specified key was too long; max key length is 3072 bytes appeared first on Redino blog.

Viewing all 80 articles
Browse latest View live




Latest Images