Example #1
0
  /** Initialize the server */
  public static void init() {
    if (initialized) return;
    org.apache.commons.logging.LogFactory.getLog(HSQLDBServer.class).info("Creating data base ...");

    server = new Server();
    server.setDatabaseName(0, "Larbc");
    server.setDatabasePath(0, "mem:Residence;sql.enforce_strict_size=true");

    server.setLogWriter(null);
    server.setErrWriter(null);
    server.setSilent(true);
    server.start();

    initialized = true;
    try {
      Class.forName("org.hsqldb.jdbcDriver");

      PrintStream out = new PrintStream(new ByteArrayOutputStream());
      Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/Larbc", "sa", "");
      SqlFile file =
          new SqlFile(
              new File(
                  FileIO.findFile(
                          "com/googlecode/projeto/larbc/rbccycle/databaseconfig/LaRBCDatabase.sql")
                      .getFile()),
              false,
              new HashMap());
      file.execute(conn, out, out, true);
      org.apache.commons.logging.LogFactory.getLog(HSQLDBServer.class)
          .info("Data base generation finished");

    } catch (Exception e) {
      org.apache.commons.logging.LogFactory.getLog(HSQLDBServer.class).error(e);
    }
  }
Example #2
0
 @Override
 public void initialize() {
   final String notificationId = ParametricStudyUtils.createDataIdentifier(study);
   Long missedNumber;
   try {
     missedNumber =
         notificationService
             .subscribe(notificationId, notificationSubscriber, platform)
             .get(notificationId);
   } catch (RemoteOperationException e) {
     LogFactory.getLog(getClass())
         .error("Failed to subscribe for Parametric Study data source: " + e.getMessage());
     return; // preserve the "old" RTE behavior for now
   }
   // process missed notifications
   if (missedNumber > MINUS_ONE) {
     if (missedNumber > StudyPublisher.BUFFER_SIZE - 1) {
       missedNumber = new Long(StudyPublisher.BUFFER_SIZE - 1);
     }
     try {
       final List<Notification> missedNotifications =
           notificationService
               .getNotifications(notificationId, platform)
               .get(notificationId)
               .subList(0, missedNumber.intValue() + 1);
       notificationSubscriber.receiveBatchedNotifications(missedNotifications);
     } catch (RemoteOperationException e) {
       LogFactory.getLog(getClass()).warn("Failed to send notifications: " + e.toString());
     }
   }
 }
  public static String getValueAsString(Object bean, String property) {
    Object value = null;

    try {
      value = PropertyUtils.getProperty(bean, property);

    } catch (IllegalAccessException e) {
      Log log = LogFactory.getLog(CustomValidatorRules.class);
      log.error(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      Log log = LogFactory.getLog(CustomValidatorRules.class);
      log.error(e.getMessage(), e);
    } catch (NoSuchMethodException e) {
      Log log = LogFactory.getLog(CustomValidatorRules.class);
      log.error(e.getMessage(), e);
    }

    if (value == null) {
      return null;
    }

    if (value instanceof String[]) {
      return ((String[]) value).length > 0 ? value.toString() : "";

    } else if (value instanceof Collection) {
      return ((Collection) value).isEmpty() ? "" : value.toString();

    } else {
      return value.toString();
    }
  }
Example #4
0
 {
   ((Log4JLogger) LogFactory.getLog("org.apache.hadoop.hdfs.StateChange"))
       .getLogger()
       .setLevel(Level.ERROR);
   ((Log4JLogger) DataNode.LOG).getLogger().setLevel(Level.ERROR);
   ((Log4JLogger) LogFactory.getLog(FSNamesystem.class)).getLogger().setLevel(Level.ERROR);
   ((Log4JLogger) DistCpV1.LOG).getLogger().setLevel(Level.ALL);
 }
 /**
  * Return a proper URL with lowercase scheme, lowercase domain, stripped hash - used to compare
  * against other previously seen URLs
  *
  * @param href A relative or absolute URL
  * @param context Null or an absolute URL to use when href is relative
  * @return
  */
 public static URL getCanonicalURL(String href, String context) {
   try {
     URI normalized;
     if (context != null) {
       normalized = new URI(context);
       if (normalized.getPath().equals("")) context += "/";
       normalized = new URI(context).resolve(href);
     } else {
       normalized = new URI(href);
     }
     normalized = normalized.normalize();
     return new URI(
             normalized.getScheme().toLowerCase(),
             normalized.getUserInfo(),
             normalized.getHost(),
             normalized.getPort(),
             normalized.getPath().equals("") ? "/" : normalized.getPath(),
             normalized.getQuery(),
             null)
         .toURL();
   } catch (URISyntaxException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   } catch (MalformedURLException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   } catch (IllegalArgumentException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   }
   /*if (href.contains("#")) {
             href = href.substring(0, href.indexOf("#"));
         }
   href = href.replace(" ", "%20");
         try {
         	URL canonicalURL;
         	if (context == null) {
         		canonicalURL = new URL(href);
         	} else {
         		canonicalURL = new URL(new URL(context), href);
         	}
         	String path = canonicalURL.getPath();
         	if (path.startsWith("/../")) {
         		path = path.substring(3);
         		canonicalURL = new URL(canonicalURL.getProtocol(), canonicalURL.getHost(), canonicalURL.getPort(), path);
         	} else if (path.contains("..")) {
         		System.out.println("Found path with ..: " + path + " " + href + " " + context);
         	}
         	return canonicalURL;
         } catch (MalformedURLException ex) {
             return null;
         }*/
 }
Example #6
0
  static {
    String defaultMetrics = System.getProperty(DEFAULT_METRICS_SYSTEM_PROPERTY);
    defaultMetricsEnabled = defaultMetrics != null;
    if (defaultMetricsEnabled) {
      String[] values = defaultMetrics.split(",");
      boolean excludeMachineMetrics = false;
      for (String s : values) {
        String part = s.trim();
        if (!excludeMachineMetrics && EXCLUDE_MACHINE_METRICS.equals(part)) {
          excludeMachineMetrics = true;
        } else {
          String[] pair = part.split("=");
          if (pair.length == 2) {
            String key = pair[0].trim();
            String value = pair[1].trim();
            try {
              if (AWS_CREDENTAIL_PROPERTIES_FILE.equals(key)) {
                final PropertiesCredentials cred;
                cred = new PropertiesCredentials(new File(value));
                credentialProvider =
                    new AWSCredentialsProvider() {
                      @Override
                      public void refresh() {}

                      @Override
                      public AWSCredentials getCredentials() {
                        return cred;
                      }
                    };
              } else if (CLOUDWATCH_REGION.equals(key)) {
                region = Regions.fromName(value);
              } else if (METRIC_QUEUE_SIZE.equals(key)) {
                Integer i = new Integer(value);
                if (i.intValue() < 1)
                  throw new IllegalArgumentException(METRIC_QUEUE_SIZE + " must be at least 1");
                metricQueueSize = i;
              } else if (QUEUE_POLL_TIMEOUT_MILLI.equals(key)) {
                Long i = new Long(value);
                if (i.intValue() < 1000)
                  throw new IllegalArgumentException(
                      QUEUE_POLL_TIMEOUT_MILLI + " must be at least 1000");
                queuePollTimeoutMilli = i;
              } else {
                LogFactory.getLog(AwsSdkMetrics.class)
                    .debug("Ignoring unrecognized parameter: " + part);
              }
            } catch (Exception e) {
              LogFactory.getLog(AwsSdkMetrics.class).debug("Ignoring failure", e);
            }
          }
        }
      }
      machineMetricsExcluded = excludeMachineMetrics;
    }
  }
  // Test pristine LogFactory instance
  public void testPristineFactory() {

    assertNotNull("LogFactory exists", factory);
    assertEquals(
        "LogFactory class",
        "org.apache.commons.logging.impl.LogFactoryImpl",
        factory.getClass().getName());

    String names[] = factory.getAttributeNames();
    assertNotNull("Names exists", names);
    assertEquals("Names empty", 0, names.length);
  }
public class RedisTaskProcessor implements TaskProcessor {

  private static final Log log = LogFactory.getLog(RedisTaskProcessor.class);
  private static final Log failCountLog = LogFactory.getLog("failLog");

  private RedisService redisService;

  public RedisService getRedisService() {
    return redisService;
  }

  public void setRedisService(RedisService redisService) {
    this.redisService = redisService;
  }

  public boolean process(String taskType, Task task) {
    RedisTask redisTask = (RedisTask) task;
    String ip = redisTask.getIp();
    String content = redisTask.getContent();
    int failCount = redisTask.getFailCount();

    if (this.addIpToContentPair(ip, content)) {
      log.info("增加ip与dataId映射到redis成功, ip=" + ip + "dataIds=" + content);
      redisTask.setFailCount(0);
      return true;
    } else {
      log.warn("增加ip与dataId映射到redis失败, ip=" + ip + "dataIds=" + content);
      failCount++;
      redisTask.setFailCount(failCount);
      if (failCount >= DiamondServerConstants.MAX_REDIS_FAIL_COUNT) {
        failCountLog.info("redis任务失败次数达到上限: ip=" + ip + ", dataIds=" + content);
        redisTask.setFailCount(0);
        return true;
      }
      return false;
    }
  }

  private boolean addIpToContentPair(String ip, String content) {
    try {
      String[] values = content.split(",");
      this.redisService.addAll("basestone-" + ip, values);
      return true;
    } catch (Exception e) {
      log.error("增加ip与发布dataId的映射到redis出错, ip为" + ip + ", dataId为" + content);
      return false;
    }
  }
}
public class ByteArrayMap extends HashMap<Integer, Class<AbstractHandler>> {

  private static final Log LOG = LogFactory.getLog(ByteArrayMap.class);
  private static final long serialVersionUID = 6578961679914231615L;

  @Override
  public Class<AbstractHandler> get(Object key) {
    return super.get(DataFactory.getInt((byte[]) key));
  }

  @Override
  public Class<AbstractHandler> put(Integer key, Class<AbstractHandler> value) {
    return super.put(key, value);
  }

  public Class<AbstractHandler> put(byte[] key, Class<AbstractHandler> value) {
    key = Arrays.copyOf(key, 4);
    return put(DataFactory.getInt(key), value);
  }

  public Class<AbstractHandler> put(String cls) {
    try {
      @SuppressWarnings("unchecked")
      Class<AbstractHandler> forName = (Class<AbstractHandler>) Class.forName(cls);
      byte[] command = forName.newInstance().getCommand();
      if (command == null) {
        throw new RuntimeException("no command return!! " + cls);
      }
      return put(command, forName);
    } catch (Exception e) {
      LOG.error(e, e);
    }
    return null;
  }
}
@Controller
public class InventoryController {

  protected final Log logger = LogFactory.getLog(getClass());

  // añadimos el autowired para que Spring pueda inyectar automáticamente
  // una referencia de la clase ProductManager
  @Autowired private ProductManager productManager;

  @RequestMapping(value = "/hello.htm")
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String now = (new Date()).toString();
    logger.info("Returning hello view with " + now);

    // Le el modelo va a ser un Map clave/valor
    Map<String, Object> myModel = new HashMap<String, Object>();
    myModel.put("now", now);
    myModel.put("products", this.productManager.getProducts());

    return new ModelAndView("hello", "model", myModel);
  }

  public void setProductManager(ProductManager productManager) {
    this.productManager = productManager;
  }
}
Example #11
0
/**
 * <a href="UpgradeTags.java.html"><b><i>View Source</i></b></a>
 *
 * @author Brian Wing Shun Chan
 */
public class UpgradeTags extends UpgradeProcess {

  public void upgrade() throws UpgradeException {
    _log.info("Upgrading");

    try {
      doUpgrade();
    } catch (Exception e) {
      throw new UpgradeException(e);
    }
  }

  protected void doUpgrade() throws Exception {

    // TagsAsset

    UpgradeTable upgradeTable =
        new DefaultUpgradeTableImpl(TagsAssetImpl.TABLE_NAME, TagsAssetImpl.TABLE_COLUMNS);

    upgradeTable.setCreateSQL(TagsAssetImpl.TABLE_SQL_CREATE);

    upgradeTable.updateTable();
  }

  private static Log _log = LogFactory.getLog(UpgradeTags.class);
}
public class MasterDaoHibernate extends HibernateDaoSupport implements MasterDao {

  protected Log log = LogFactory.getLog(getClass());

  public void deleteMaster(Master master) {
    getHibernateTemplate().delete(master);
  }

  public Master getMasterById(Long id) {
    return (Master) getHibernateTemplate().get(Master.class, id);
  }

  public void saveMaster(Master master) {
    getHibernateTemplate().saveOrUpdate(master);
  }

  public void updateMaster(Master master) {
    getHibernateTemplate().merge(master);
  }

  public void saveMasterImage(MasterWallpaper masterImage) {
    getHibernateTemplate().saveOrUpdate(masterImage);
  }

  public List<MasterWatermark> getWatermarks() {
    return getHibernateTemplate().find("from MasterWatermark where is_deleted = false");
  }

  public String toString() {
    return "MasterDaoHibernate";
  }
}
Example #13
0
 /**
  * Initialize all services define in the {@link #CONF_SERVICE_CLASSES} configuration property.
  *
  * @throws ServiceException thrown if any of the services could not initialize.
  */
 @SuppressWarnings("unchecked")
 public void init() throws ServiceException {
   XLog log = new XLog(LogFactory.getLog(getClass()));
   log.trace("Initializing");
   SERVICES = this;
   try {
     Class<? extends Service>[] serviceClasses =
         (Class<? extends Service>[]) conf.getClasses(CONF_SERVICE_CLASSES);
     if (serviceClasses != null) {
       for (Class<? extends Service> serviceClass : serviceClasses) {
         setService(serviceClass);
       }
     }
   } catch (RuntimeException ex) {
     XLog.getLog(getClass()).fatal(ex.getMessage(), ex);
     throw ex;
   } catch (ServiceException ex) {
     SERVICES = null;
     throw ex;
   }
   InstrumentationService instrService = get(InstrumentationService.class);
   if (instrService != null) {
     for (Service service : services.values()) {
       if (service instanceof Instrumentable) {
         ((Instrumentable) service).instrument(instrService.get());
       }
     }
   }
   log.info("Initialized");
   log.info("Oozie System ID [{0}] started!", getSystemId());
 }
/**
 * @author tmo
 * @version $Id$
 * @todo description
 */
public class QueryEvaluate implements EventExecution {
  /** Logger for this class */
  private static final Log LOG = LogFactory.getLog(QueryEvaluate.class);

  /** @param _parameter */
  public Return execute(final Parameter _parameter) throws EFapsException {
    Return ret = new Return();
    Map properties = (Map) _parameter.get(ParameterValues.PROPERTIES);

    String types = (String) properties.get("Types");

    boolean expandChildTypes = "true".equals((String) properties.get("ExpandChildTypes"));

    if (LOG.isDebugEnabled()) {
      LOG.debug("types=" + types);
    }

    SearchQuery query = new SearchQuery();
    query.setQueryTypes(types);
    query.setExpandChildTypes(expandChildTypes);
    query.addSelect("OID");
    query.execute();

    List<List<Instance>> list = new ArrayList<List<Instance>>();
    while (query.next()) {
      List<Instance> instances = new ArrayList<Instance>(1);
      instances.add(new Instance((String) query.get("OID")));
      list.add(instances);
    }

    ret.put(ReturnValues.VALUES, list);

    return ret;
  }
}
Example #15
0
 /** Exports AwsSdkMetrics for JMX access. */
 static {
   try {
     MBeans.registerMBean(MBEAN_OBJECT_NAME, new AwsSdkMetrics.Admin());
   } catch (Exception ex) {
     LogFactory.getLog(AwsSdkMetrics.class).warn("", ex);
   }
 }
/**
 * Cleans up committed transactions when they are no longer needed to verify pending transactions.
 */
public class CleanOldTransactionsChore extends Chore {

  private final TrxRegionEndpoint trx_Region;

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

  /**
   * @param trx_Region
   * @param timer
   * @param stoppable
   */
  public CleanOldTransactionsChore(
      final TrxRegionEndpoint trx_Region, final int timer, final Stoppable stoppable) {
    super("CleanOldTransactionsChore", timer, stoppable);
    this.trx_Region = trx_Region;
  }

  @Override
  public void chore() {

    trx_Region.removeUnNeededCommitedTransactions();

    // if (LOG.isDebugEnabled()) LOG.debug("Trafodion ChoreThread CP Epoch " +
    // trx_Region.controlPointEpoch.get());

    trx_Region.choreThreadDetectStaleTransactionBranch();

    // LOG.trace("CleanOldTransactionsChore: region " + this.trx_Region.getRegionNameAsString());

    trx_Region.removeUnNeededStaleScanners();
  }
}
public class HolidayManagerImpl implements HolidayManager {
  private static Log log = LogFactory.getLog(HolidayManagerImpl.class);
  private HolidayDao dao;

  public void setHolidayDao(HolidayDao dao) {
    this.dao = dao;
  }

  @Override
  public List<Holiday> getHolidays(Date begin, Date end) {
    return dao.getHolidays(begin, end);
  }

  @Override
  public Holiday get(Integer id) {
    return dao.getHoliday(id);
  }

  @Override
  public void remove(Integer id) {
    dao.remove(dao.getHoliday(id));
  }

  @Override
  public void save(Holiday h) {
    dao.save(h);
  }

  @Override
  public void applyHolidays() {
    dao.applyHolidays();
  }
}
Example #18
0
public class Sample0 extends SynapseTestCase {

  private static final Log log = LogFactory.getLog(Sample0.class);

  private StockQuoteSampleClient client;

  public Sample0() {
    super(0);
    client = getStockQuoteClient();
  }

  public void testSmartClientMode() {
    String addUrl = "http://localhost:9000/services/SimpleStockQuoteService";
    String trpUrl = "http://localhost:8280/";

    log.info("Running test: Smart Client mode");
    SampleClientResult result = client.requestStandardQuote(addUrl, trpUrl, null, "IBM", null);
    assertResponseReceived(result);
  }

  public void testSynapseAsHTTPProxy() {
    String addUrl = "http://localhost:9000/services/SimpleStockQuoteService";
    String prxUrl = "http://localhost:8280/";

    log.info("Running test: Using Synapse as a HTTP Proxy");
    SampleClientResult result = client.requestStandardQuote(addUrl, null, prxUrl, "IBM", null);
    assertResponseReceived(result);
  }
}
@Component("blCartStateFilter")
/**
 * This filter should be configured after the BroadleafCommerce CustomerStateFilter listener from
 * Spring Security. Retrieves the cart for the current BroadleafCommerce Customer based using the
 * authenticated user OR creates an empty non-modifiable cart and stores it in the request.
 *
 * @author bpolster
 */
public class CartStateFilter extends GenericFilterBean implements Ordered {

  /** Logger for this class and subclasses */
  protected final Log LOG = LogFactory.getLog(getClass());

  @Resource(name = "blCartStateRequestProcessor")
  protected CartStateRequestProcessor cartStateProcessor;

  @Override
  @SuppressWarnings("unchecked")
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    cartStateProcessor.process(
        new ServletWebRequest((HttpServletRequest) request, (HttpServletResponse) response));
    chain.doFilter(request, response);
  }

  @Override
  public int getOrder() {
    // FilterChainOrder has been dropped from Spring Security 3
    // return FilterChainOrder.REMEMBER_ME_FILTER+1;
    return 1502;
  }
}
public class ConcurrentAccessReplicator {

  private static final Log log = LogFactory.getLog(ConcurrentAccessReplicator.class);
  private ConfigurationContext configContext;

  public ConcurrentAccessReplicator(ConfigurationContext configContext) {
    this.configContext = configContext;
  }

  public void replicate(String key, ConcurrentAccessController concurrentAccessController) {
    try {
      ClusteringAgent clusteringAgent = configContext.getAxisConfiguration().getClusteringAgent();
      if (clusteringAgent != null) {
        if (log.isDebugEnabled()) {
          log.debug("Replicating ConcurrentAccessController " + key + " in a ClusterMessage.");
        }
        clusteringAgent.sendMessage(
            new ConcurrentAccessUpdateClusterMessage(key, concurrentAccessController), true);
      }
    } catch (ClusteringFault e) {
      if (log.isErrorEnabled()) {
        log.error("Could not replicate throttle data", e);
      }
    }
  }
}
Example #21
0
 /** Destroy all services. */
 public void destroy() {
   XLog log = new XLog(LogFactory.getLog(getClass()));
   log.trace("Shutting down");
   boolean deleteRuntimeDir = false;
   if (conf != null) {
     deleteRuntimeDir = conf.getBoolean(CONF_DELETE_RUNTIME_DIR, false);
   }
   if (services != null) {
     List<Service> list = new ArrayList<Service>(services.values());
     Collections.reverse(list);
     for (Service service : list) {
       try {
         log.trace("Destroying service[{0}]", service.getInterface());
         if (service.getInterface() == XLogService.class) {
           log.info("Shutdown");
         }
         service.destroy();
       } catch (Throwable ex) {
         log.error(
             "Error destroying service[{0}], {1}", service.getInterface(), ex.getMessage(), ex);
       }
     }
   }
   if (deleteRuntimeDir) {
     try {
       IOUtils.delete(new File(runtimeDir));
     } catch (IOException ex) {
       log.error("Error deleting runtime directory [{0}], {1}", runtimeDir, ex.getMessage(), ex);
     }
   }
   services = null;
   conf = null;
   SERVICES = null;
 }
@Service
public class AutoDiscoveryService {

  private static final Log log = LogFactory.getLog(AutoDiscoveryService.class);

  private final AutoDiscoveryPublisher publisher;

  @Inject
  public AutoDiscoveryService(AutoDiscoveryPublisher publisher) {
    this.publisher = publisher;
  }

  @PostConstruct
  public void init() {
    new Thread(
            new Runnable() {

              @Override
              public void run() {
                log.info("Started publishing picture sucker service for auto discovery");
                publisher.start();
              }
            })
        .start();
  }
}
@Component
@Scope("request")
public class SettleStatusAction extends BaseAction {
  private final transient Log logger = LogFactory.getLog(SettleStatusAction.class);

  @Autowired
  @Qualifier("clearStatusService")
  private ClearStatusService clearStatusService;

  public InService getService() {
    return this.clearStatusService;
  }

  public int getSettleStatus() {
    int status = 0;
    int count = 0;
    List<ClearStatus> list = this.clearStatusService.getList(null, null);
    for (ClearStatus clearStatus : list) {
      if ("Y".equals(clearStatus.getStatus())) {
        count++;
      }
    }
    if (count == list.size()) {
      status = 1;
    } else if ((count != 0) && (count < list.size())) {
      status = 2;
    }
    return status;
  }
}
/** Main Spring boot configuration file. Starts up a Spring boot application. */
@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@Import({RepositoryRestMvcConfiguration.class})
@ComponentScan
@EnableSwagger
public class Application {

  private static final Log log = LogFactory.getLog(Application.class);

  public static void main(String[] args) {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    SpringApplication app = new SpringApplication(Application.class);
    app.addListeners(
        new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {
          @Override
          public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
            MDC.put("appName", event.getEnvironment().getProperty("project.name"));
            MDC.put("requestId", "N/A");
            try {
              MDC.put("hostName", InetAddress.getLocalHost().getHostName());
            } catch (IllegalArgumentException | UnknownHostException e) {
              log.info(e);
            }
          }
        });
    ApplicationContext ctx = app.run(args);
    log.info("-----------------------------------------------------------------");
    log.info("Active profiles:");
    Arrays.asList(ctx.getEnvironment().getActiveProfiles()).forEach(log::info);
    log.info("-----------------------------------------------------------------");
  }
}
Example #25
0
public class LoginInterceptor extends HandlerInterceptorAdapter {
  private static final Log logger = LogFactory.getLog(LoginInterceptor.class);
  private static final String showLogin = "******";
  private static final String login = "******";

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    Object usrLogin = request.getSession().getAttribute(Constants.SESS_USER_KEY);
    String sevPath = request.getServletPath();
    logger.info("ServletPath: " + sevPath);
    String rootPath = "";
    if (!StringUtil.isBlankOrNull(sevPath)
        && !sevPath.equals("/" + showLogin)
        && !sevPath.equals("/" + login)) {
      int len = sevPath.split("/").length;
      for (int i = 2; i < len; i++) {
        rootPath += "../";
      }
      if (usrLogin == null) {
        // response.sendRedirect(rootPath+showLogin);
        StringBuffer toLoginScript = new StringBuffer();
        toLoginScript.append("<script type=\"text/javascript\">");
        toLoginScript.append("top.window.location=\"" + rootPath + showLogin + "\"");
        toLoginScript.append("</script>");
        logger.info(toLoginScript);
        PrintWriter writer = response.getWriter();
        writer.write(toLoginScript.toString());
        writer.flush();
      }
    }
    return true;
  }
}
public final class LaunchHelpAction extends AbstractDesignerContextAction {
  private static final Log log = LogFactory.getLog(LaunchHelpAction.class);

  public LaunchHelpAction() {
    putValue(Action.NAME, ActionMessages.getString("LaunchHelpAction.Text"));
    putValue(Action.SHORT_DESCRIPTION, ActionMessages.getString("LaunchHelpAction.Description"));
    putValue(Action.MNEMONIC_KEY, ActionMessages.getOptionalMnemonic("LaunchHelpAction.Mnemonic"));
    putValue(
        Action.ACCELERATOR_KEY,
        ActionMessages.getOptionalKeyStroke("LaunchHelpAction.Accelerator"));
  }

  /** Invoked when an action occurs. */
  public void actionPerformed(final ActionEvent e) {
    final Configuration config = ReportDesignerBoot.getInstance().getGlobalConfig();
    final String docUrl =
        config.getConfigProperty(
            "org.pentaho.reporting.designer.core.documentation.report_designer_user_guide");

    try {
      ExternalToolLauncher.openURL(docUrl);
    } catch (IOException ex) {
      log.warn("Could not load " + docUrl, ex); // NON-NLS
    }
  }
}
Example #27
0
public class PropsComponent implements Callable {
  private static final Log logger = LogFactory.getLog(PropsComponent.class);

  protected static Apple testObjectProperty = new Apple();

  public Object onCall(UMOEventContext context) throws Exception {
    logger.debug("org.mule.test.usecases.props.PropsComponent");

    if ("component1".equals(context.getComponent().getName())) {
      logger.debug("Adding: " + context.getComponent().getName());
      Map props = new HashMap();
      props.put("stringParam", "param1");
      props.put("objectParam", testObjectProperty);
      UMOMessage msg = new MuleMessage(context.getMessageAsString(), props);
      logger.debug("Adding done: " + context.getComponent().getName());
      return msg;
    } else {
      logger.debug("Verifying: " + context.getComponent().getName());
      assertEquals("param1", context.getMessage().getProperty("stringParam"));
      assertEquals(testObjectProperty, context.getMessage().getProperty("objectParam"));
      logger.debug("Verifying done: " + context.getComponent().getName());
    }

    return context;
  }

  protected static void assertEquals(Object theObject, Object theProperty) {
    if (!theObject.equals(theProperty)) {
      logger.error(String.valueOf(theObject) + " does not equal:" + String.valueOf(theProperty));
    } else {
      logger.debug("Woohoo!");
    }
  }
}
Example #28
0
/**
 * The &lt;invoke&gt; tag will invoke a given Script instance. It can be used with the
 * &lt;script&gt; tag which defines scripts as variables that can later be invoked by this
 * &lt;invoke&gt; tag.
 *
 * @author <a href="mailto:[email protected]">James Strachan</a>
 * @version $Revision: 155420 $
 */
public class InvokeTag extends TagSupport {

  /** The Log to which logging calls will be made. */
  private static final Log log = LogFactory.getLog(InvokeTag.class);

  private Script script;

  public InvokeTag() {}

  /**
   * Sets the Script to be invoked by this tag, which typically has been previously defined by the
   * use of the &lt;script&gt; tag.
   */
  public void setScript(Script script) {
    this.script = script;
  }

  // Tag interface
  // -------------------------------------------------------------------------
  public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
    if (script == null) {
      throw new MissingAttributeException("script");
    }
    script.run(context, output);
  }
}
public class SyncThreadPoolScriptRunnerService extends ThreadPoolScriptRunnerService {
  private static final Log log = LogFactory.getLog(ThreadPoolScriptRunnerService.class);

  @Override
  protected void runInternal(final ScriptRunner scriptRunner, final Binding binding) {
    createExecutorService();

    final Object monitor = new Object();

    executorService.execute(
        new Runnable() {
          @Override
          public void run() {
            try {
              scriptRunner.callback(webDriverService.getWebDriver(), binding);
            } catch (Exception e) {
              log.error(e.getMessage(), e);
              binding.put(EXCEPTION_KEY, e);
            } finally {
              synchronized (monitor) {
                monitor.notify();
              }
            }
          }
        });

    synchronized (monitor) {
      try {
        monitor.wait();
      } catch (InterruptedException e) {
        /* ignore */
      }
    }
  }
}
/**
 * This class contains the logic that is run every time this module is either started or stopped.
 */
public class admintoolsuiActivator implements ModuleActivator {

  protected Log log = LogFactory.getLog(getClass());

  /** @see ModuleActivator#willRefreshContext() */
  public void willRefreshContext() {
    log.info("Refreshing admintoolsui Module");
  }

  /** @see ModuleActivator#contextRefreshed() */
  public void contextRefreshed() {
    log.info("admintoolsui Module refreshed");
  }

  /** @see ModuleActivator#willStart() */
  public void willStart() {
    log.info("Starting admintoolsui Module");
  }

  /** @see ModuleActivator#started() */
  public void started() {
    log.info("admintoolsui Module started");
  }

  /** @see ModuleActivator#willStop() */
  public void willStop() {
    log.info("Stopping admintoolsui Module");
  }

  /** @see ModuleActivator#stopped() */
  public void stopped() {
    log.info("admintoolsui Module stopped");
  }
}